CommonJS 和 ES6 模块主要区别

209 阅读1分钟

CommonJS-require 和 ES6-import 主要区别:

它们有三个重大差异。

1.CommonJS 模块输出的是一个值的拷贝,ES6 模块输出的是值的引用。

CommonJS-require运行时加载的是一个对象如下:

// lib.js
var counter = 3;
function incCounter() {
  counter++;
}
module.exports = {
  counter: counter,
  incCounter: incCounter,
};

// lib2.js
var counter = 3;
function incCounter() {
  counter++;
}
module.exports = {
  get counter() {
    return counter
  },
  incCounter: incCounter,
};

// main.js
var mod = require('./lib');
//  output mod is:
// { counter: 3, incCounter: [Function: incCounter] }
console.log(mod.counter);  // 3
mod.incCounter();
console.log(mod.counter);  // 3


//  main2.js
var mod = require('./lib2');
// output mod is:
// { counter: [Getter], incCounter: [Function: incCounter] }
console.log(mod.counter);  // 3
mod.incCounter();
console.log(mod.counter); // 4

ES6-import编译时加载实际上是静态代码段的导入。

lib.mjs
export let counter = 3;
export function incCounter() {
    counter++;
}

main.mjs
import * as m from './lib.mjs';
console.dir(m);
console.log(m.counter); // 3
m.incCounter();
console.log(m.counter); // 4

output:
[Module: null prototype] {
  counter: 3,
  incCounter: [Function: incCounter]
}
3
4

//这里不能赋值,否则不能报错。
m.counter++;
TypeError: Cannot assign to read only property 'counter' of object '[object Module]'

2.CommonJS 模块是运行时加载,ES6 模块是编译时输出接口。

这就决定了CommonJS在代码的任何位置都可导入, ES6模块只能在文件开头导入。

3.CommonJS 模块的require()是同步加载模块,ES6 模块的import命令是异步.

参考:阮一峰-ECMAScript6 入门