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

一、标准不同

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

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值