CommonJS 中的 require/exports 和 ES6 中的 import/export 区别

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_40283784/article/details/87128124

一、标准不同

CommonJS 中的 require/exports 和比ES6 中的 import/export出现得早,node.js是他的实现;CommonJS 中的 require/exports 是老的标准,ES6 中的 import/export要比它更加权威。es6通过babel转化为es5执行,所以写的import/export是通过babel转换为require/exports执行的。二者其实都可以看做是输出一个对象和引入一个对象并使用其中的属性或方法。

二、书写格式不同

这个太简单了,不作鳌述。

三、加载机制不同

CommonJS 中的 require/exports是运行时加载,就是说它没办法进行编译处理和优化。而ES6 中的 import/export是运行时加载,即在静态编译时就已经包含了需要导入导出的模块。下面这个例子:

// counter.js
exports.count = 0
setTimeout(function () {
  console.log('increase count to', ++exports.count, 'in counter.js after 500ms')
}, 500)

// commonjs.js
const {count} = require('./counter')
setTimeout(function () {
  console.log('read count after 1000ms in commonjs is', count)
}, 1000)

//es6.js
import {count} from './counter'
setTimeout(function () {
  console.log('read count after 1000ms in es6 is', count)
}, 1000)
➜  test node commonjs.js
//因为是运行时才加载这个模块,所以导出的count没有经过计时器,依旧是0
increase count to 1 in counter.js after 500ms
read count after 1000ms in commonjs is 0
➜  test babel-node es6.js
//因为是编译时已经编译了这个模块,所以导出的count经过计时器就已经为1了
increase count to 1 in counter.js after 500ms
read count after 1000ms in es6 is 1

猜你喜欢

转载自blog.csdn.net/qq_40283784/article/details/87128124