1.在没有es6前,最主要的有 CommonJS 和 AMD 两种。前者用于服务器,后者用于浏览器。
// CommonJS模块
let { stat, exists, readFile } = require('fs');
// 等同于
let _fs = require('fs');
let stat = _fs.stat;
let exists = _fs.exists;
let readfile = _fs.readfile;
所有属性方法加载,再取出三个属性,生成对象,这种叫运行时加载
// ES6模块
import { stat, exists, readFile } from 'fs';
运行时加载,只加载三个属性,这种加载称为“编译时加载”或者静态加载,当然,这也导致了没法引用 ES6 模块本身,因为它不是对象。
2.export
export导出的是文件,是模块,内部的变量外界无法获取,除非export出来,并且只能读取,不能修改;
优先考虑的导出方式
var firstName = 'Michael';
var lastName = 'Jackson';
var year = 1958;
export { firstName, lastName, year };
export语句输出的接口,与其对应的值是动态绑定关系,即通过该接口,可以取到模块内部实时的值。
export var foo = 'bar';
setTimeout(() => foo = 'baz', 500);
上面代码输出变量foo,值为bar,500 毫秒之后变成baz。
这一点与 CommonJS 规范完全不同。CommonJS 模块输出的是值的缓存,不存在动态更新
3.import
a是一个只读的接口。但是,如果a是一个对象,改写a的属性是允许的(但很作死,最好别)
import {a} from './xxx.js'
a.foo = 'hello'; // 合法操作
注意,import命令具有提升效果,会提升到整个模块的头部,首先执行。
import 可以 用 *
指定一个对象,实现整体加载
import { area, circumference } from './circle';
console.log('圆面积:' + area(4));
console.log('圆周长:' + circumference(14));
import * as circle from './circle';
console.log('圆面积:' + circle.area(4));
console.log('圆周长:' + circle.circumference(14));
4.export default 命令
匿名导出,,一个模块只能有一个默认输出,因此export default命令只能使用一次,唯一性。
// 第一组
export default function crc32() { // 输出
// ...
}
//函数有没有名字都不重要
import crc32 from 'crc32'; // 输入
// 第二组
export function crc32() { // 输出
// ...
};
import {crc32} from 'crc32'; // 输入
5.export 与 import 的复合写法
export { foo, bar } from 'my_module';
// 可以简单理解为
import { foo, bar } from 'my_module';
export { foo, bar };
先导入再导出,搭了个桥,当前模块不能直接使用foo和bar
可以用于模块的接口改名和整体输出
6.跨模块常量
说白了就是公共变量,如果要使用的常量非常多,可以建一个专门的constants目录,将各种常量写在不同的文件里面,保存在该目录下。
// constants/db.js
export const db = {
url: 'http://my.couchdbserver.local:5984',
admin_username: 'admin',
admin_password: 'admin password'
};
// script.js
import {db} from './constants/index';
7.import()
前面提到,import是静态分析,类似java的static,先于模块内的其他语句执行,因此不能用if条件加载,因为require是运行时加载模块,import命令无法取代require的动态加载功能
const path = './' + fileName;
const myModual = require(path);
因此,就有了import()这个提案
下面是import()的一些适用场合
(1)按需加载
button.addEventListener('click', event => {
import('./dialogBox.js')
.then(dialogBox => {
dialogBox.open();
})
.catch(error => {
/* Error handling */
})
});
上面代码中,import()方法放在click事件的监听函数之中,只有用户点击了按钮,才会加载这个模块
(2)条件加载
(3)动态的模块路径
import(f())
.then(...);
上面代码中,根据函数f的返回结果,加载不同的模块。
注意:
import()加载模块成功以后,这个模块会作为一个对象,当作then方法的参数。因此,可以使用对象解构赋值的语法,获取输出接口。
8.浏览器加载模块
1.默认情况下,浏览器是同步加载 JavaScript 脚本,即渲染引擎遇到<script>
标签就会停下来,等到执行完脚本,再继续向下渲染。如果是外部脚本,还必须加入脚本下载的时间。
<script src="path/to/myModule.js" defer></script>
<script src="path/to/myModule.js" async></script>
defer与async的区别是:defer要等到整个页面在内存中正常渲染结束(DOM 结构完全生成,以及其他脚本执行完成),才会执行;async一旦下载完,渲染引擎就会中断渲染,执行这个脚本以后,再继续渲染。一句话,defer是“渲染完再执行”,async是“下载完就执行”。另外,如果有多个defer脚本,会按照它们在页面出现的顺序加载,而多个async脚本是不能保证加载顺序的。
2.浏览器加载 ES6 模块,也使用
<script type="module" src="./foo.js"></script>
<!-- 等同于 -->
<script type="module" src="./foo.js" defer></script>
注意: 模块之中,顶层的this关键字返回undefined,而不是指向window。也就是说,在模块顶层使用this关键字,是无意义的。
9.ES6 模块与 CommonJS 模块的差异
- CommonJS 模块输出的是一个值的拷贝,ES6 模块输出的是值的引用。
- CommonJS 模块是运行时加载,ES6 模块是编译时输出接口。
- ES6 模块之中,顶层的this指向undefined;CommonJS 模块的顶层this指向当前模块
// lib.js
var counter = 3;
function incCounter() {
counter++;
}
module.exports = {
counter: counter,
incCounter: incCounter,
};
// main.js
var mod = require('./lib');
console.log(mod.counter); // 3
mod.incCounter();
console.log(mod.counter); // 3
ES6模块,是引用,值是活的,动态加载
// lib.js
export let counter = 3;
export function incCounter() {
counter++;
}
// main.js
import { counter, incCounter } from './lib';
console.log(counter); // 3
incCounter();
console.log(counter); // 4
10.ES6 模块加载 CommonJS 模块
// a.js
module.exports = {
foo: 'hello',
bar: 'world'
};
// 等同于
export default {
foo: 'hello',
bar: 'world'
};
import命令加载上面的模块,module.exports会被视为默认输出,即import命令实际上输入的是这样一个对象{ default: module.exports }。
所以,一共有三种写法,可以拿到 CommonJS 模块的module.exports。
// 写法一
import baz from './a';
// baz = {foo: 'hello', bar: 'world'};
// 写法二
import {default as baz} from './a';
// baz = {foo: 'hello', bar: 'world'};
// 写法三
import * as baz from './a';
// baz = {
// get default() {return module.exports;},
// get foo() {return this.default.foo}.bind(baz),
// get bar() {return this.default.bar}.bind(baz)
// }
11.CommonJS 模块加载 ES6 模块
CommonJS 模块加载 ES6 模块,不能使用require命令,而要使用import()
函数。ES6 模块的所有输出接口,会成为输入对象的属性。
// es.mjs
let foo = { bar: 'my-default' };
export default foo;
// cjs.js
const es_namespace = await import('./es.mjs');
// es_namespace = {
// get default() {
// ...
// }
// }
console.log(es_namespace.default);
// { bar:'my-default' }
12.CommonJS 模块的循环加载
“循环加载”(circular dependency)指的是,a脚本的执行依赖b脚本,而b脚本的执行又依赖a脚本。
//a.js
exports.done = false;
var b = require('./b.js');//运行到这停止,等待b.js执行完
console.log('在 a.js 之中,b.done = %j', b.done);
exports.done = true;
console.log('a.js 执行完毕');
//b.js
exports.done = false;
var a = require('./a.js');
//糟了,等待a.js执行完,这时,就发生了“循环加载”。系统会去a.js模块对应对象的exports属性取值,可是因为a.js还没有执行完,从exports属性只能取回已经执行的部分,而不是最后的值。
a.js已经执行的部分,只有一行。
console.log('在 b.js 之中,a.done = %j', a.done);
exports.done = true;
console.log('b.js 执行完毕');
//main.js
var a = require('./a.js');
var b = require('./b.js');
console.log('在 main.js 之中, a.done=%j, b.done=%j', a.done, b.done);
输出结果:
在 b.js 之中,a.done = false
b.js 执行完毕
在 a.js 之中,b.done = true
a.js 执行完毕
在 main.js 之中, a.done=true, b.done=true
13.ES6 模块的循环加载
ES6 模块是动态引用,如果使用import从一个模块加载变量(即import foo from 'foo'
),那些变量不会被缓存,而是成为一个指向被加载模块的引用
// a.mjs
import {bar} from './b';//执行b
console.log('a.mjs');
console.log(bar);
export let foo = 'foo';
// b.mjs
import {foo} from './a';
console.log('b.mjs');
console.log(foo);
export let bar = 'bar';
$ node --experimental-modules a.mjs
b.mjs
ReferenceError: foo is not defined
已知它从a.mjs输入了foo接口,这时不会去执行a.mjs,而是认为这个接口已经存在了,继续往下执行。执行到第三行console.log(foo)的时候,才发现这个接口根本没定义,因此报错。
想要成功运行,就需要先声明函数变量。
最后,本篇文章参考阮一峰先生的ECMAScript 6 入门教材,仅为个人学习记录,欢迎转载。