喜闻乐见,ES6有了module语法,js有了模块体系
模块加载的介质是接口,而形成依赖关系的文件之间,一方需要对外接口,另一方需要通过接口加载模块,module的核心就是export和import了。
export
export var a = 'i want to export sth1'
export var b = 'i want to export sth2'
export var c = 'i want to export sth3'
var a = 'i want to export sth1'
var b = 'i want to export sth2'
var c = 'i want to export sth3'
export {a,b,c}
export function test(){...}
function test1(){..}
function test2(){..}
export {
test1 as aliase1,
test2 as aliase2,
test2 as aliase3
要注意的点:
1.如果选择先声明变量,再声明接口的方式,声明接口时必须带花括号,否则会报错。
2.export语句输出的接口,与其对应的值是动态绑定关系,即通过该接口,可以取到模块内部实时的值。
3.export命令可以出现在模块的任何位置,只要处于模块顶层就可以。如果处于块级作用域内,就会报错。
import
语法:
假设接口文件为mytest.js
import {test1} from './mytest'
import {test1 as newname} from './mytest'
//整体加载用*号表示
import * as test from './mytest'
test.test1();
test.test2();
要注意的点:
1.js文件可省略后缀
2.from指定模块文件的位置,可以是相对路径,也可以是绝对路径
3.如果from后面只是模块名,不带有路径,那么必须有配置文件,告诉 JavaScript 引擎该模块的位置。
4.import命令具有提升效果,会提升到整个模块的头部,首先执行。
5.import是静态执行,所以不能使用表达式和变量
6.整体加载是不可以改变对象的。
默认输出export default
这是在使用vue时常见的。
//默认输出一个函数
export default function () {
console.log('foo');
}
//引入模块时可任意命名
import customName from './export-default';
customName(); // 'foo'
//输出非匿名函数
export default function foo() {
console.log('foo');
}
// 或者写成
function foo() {
console.log('foo');
}
export default foo;
//即便是非匿名函数,使用了默认输出,就被当作匿名函数加载了
// 默认
export default function crc32() { // 输出
// ...
}
import crc32 from 'crc32'; // 输入
// 非默认
export function crc32() { // 输出
// ...
};
import {crc32} from 'crc32'; // 输入
//其实export default语义是将某变量值赋给变量default
// 正确
var a = 1;
export default a;
// 错误
export default var a = 1;
// 正确
export default 42;
// 报错
export 42;
复合写法
如果在一个模块之中,先输入后输出同一个模块,import语句可以与export语句写在一起。
export { foo, bar } from 'my_module';
// 等同于
import { foo, bar } from 'my_module';
export { foo, bar };
import()
可完成动态加载,接收参数可以为import的所有可能参数
import()加载模块成功以后,这个模块会作为一个对象,当作then方法的参数。因此,可以使用对象解构赋值的语法,获取输出接口。
import('./myModule.js')
.then(({export1, export2}) => {
// ...·
});
网友评论