ES6:Module的语法入门
export命令
-
ES6提供了两种export方式:
//profile.js export var a = 1; export var b = 2; export function c(x,y){ return x+y; }; //profile.js var a = 1; var b = 2; function c(x,y){ return x+y; }; export { a,b,c};
-
可以使用as关键字重命名变量或函数:
//profile.js var a = 1; export { a as A};
-
注意表达方式
//以下声明都是错误的! export 1; var m = 1; export m; //正确写法 export var m = 1; var m = 1; export { m}
-
export语句输出的接口与其对应的值是动态绑定的!
export var a = 1; setTimeout(()=>{ a = 2; },1000); //1s后,a的值变成了2;
import命令
-
基本语法
import { a,b,c} from './profile';
- import同样可以使用as进行重命名
import { a as A} from './profile';
-
import 命令具有提升效果,会提升到整个模块头部;
-
import命令中的路径不允许使用变量代替,原因是import是静态执行的;
-
重复输入相同的import语句,只会执行一次;
模块整体加载
-
有时候,我们想加载整个模块,可以用下列方法实现
//profile.js export var a = 1; export var b = 2; export function c(x,y){ return x+y; }; //main.js import * as profile from './profile'; console.log(profile.a); console.log(profile.b);
-
注意:不能在import的模块中添加属性
export default命令
-
为了方便用户,使其不用阅读文档就能够加载模块,可以用export default命令为模块指定输出。
-
使用export default命令输出的文件,在import时可以为其命名;
//profile.js //这里的函数可名命也可匿名 export default function foo(){ console.log('heihei'); } //main.js import heihei from './profile'; heihei(); //"heihei"
-
本质上,export default就是输出一个叫做default的变量或者方法,然后系统允许我们为它起名字,因此,下面的写法是有效的。
// module.js function foo(){ console.log('foo'); } export { foo as default} //等同于 export default foo; // main.js import { default as hehe} from './module.js' import hehe from './module.js'
-
正因为default是变量,所以后面不能跟声明语句。
// 正确 export var a = 1; //错误 export default var a = 1;
-
export也可以用来输出类
// profile.js export default Myclass; //main.js import hisclass from './profile.js'; let a = new hisclass();
export 和 import 的混合用法
-
如果想在一个模块中先输入后输出同一个模块,可以混合使用两个语法
export { foo,bar} from './profile.js'; // 等同于 import { foo,bar} from './profile.js'; export { foo,bar}; // 整体输出 export * from './profile.js';
-
具名接口输出为默认接口
export { foo as default} from './profile.js' //等同于 import { foo} from './profile.js'; export default foo;
跨模块常量
-
我们知道,const声明的常量只在当前代码块里有效,若想跨模块共享const,可采用下面方法。
// constants.js export const A= 1; // main.js import * as constants from './constants.js'; import { A} from './constants.js'; console.log(A); // 1 console.log(constants.A); // 1
import的注意事项
-
import和export命令在javascript中会被静态解析,因此会先于其他模块执行,因此不能放在if语句里,必须放在所有模块的顶层;
-
require语法是动态解析的,import是静态解析的,因此,可通过import()函数来进行动态加载;
import('./mymodule.js') .then(module=>{ console.log(module.a); })
-
import()函数返回一个promise对象,与require的区别是,前者是是异步加载,后者是同步加载;
-
若想同时加载多个模块,可采用Promise.all方法。
Promise.all( import('./module1.js'), import('./module2.js') ).then(([module1,module2])=>{ ...... })