ES Module 和 CommonJS2 的区别
- ES Module 是 ES 标准里的模块定义语法,CommonJS2 则是 Node.js 社区的民间约定
- ES Module 使用 import 和 export 关键字,CommonJS2 则使用 require 函数和 exports 对象
- ES Modules 对模块采用了「动态只读引用」,而 CommonJS2 则是简单的浅复制
在浏览器上直接运行带有 import 关键字的代码,需要使用现代浏览器,并且在 script 标签上添加 type="module" 属性
//name.js
let name = 'William';
let hobbies = ['coding'];
setTimeout(() => {
name = 'Yvette';
hobbies.push('reading');
}, 300);
module.exports = { name, hobbies };
//index.js
const { name, hobbies } = require('./name');
console.log(name); //William
console.log(hobbies); //['coding']
/*
* name 的值没有受到影响,因为 {name: name} 属性值 name 存的是个字符串
* 300ms后 name 变量重新赋值,但是不会影响 {name: name}
*
* hobbies 的值会被影响,因为 {hobbies: hobbies} 属性值 hobbies 中存的是
* 数组的堆内存地址,因此当 hobbies 对象的值被改变时,存在栈内存中的地址并
没有发生变化,因此 hoobies 对象值的改变会影响 {hobbies: hobbies}
* xx = { name, hobbies } 也因此改变 (复杂数据类型,拷贝的栈内存中存的地址)
*/
setTimeout(() => {
console.log(name);//William
console.log(hobbies);//['coding', 'reading']
}, 500)
摘自:https://github.com/YvetteLau/Step-By-Step/issues/43
编译import和export关键字
const {code:es5Code} = babel.transform(code,{
presets:['@babel/preset-env']
})
编译前:
import b from './b.js'
const a = {
value: 'a',
getB: () => b.value + ' from a.js'
}
export default a
编译后:
// 开启严格模式
"use strict";
/*
* 添加__esModule:true 属性,和CommonJS模块区分开
* Object.defineProperty(obj, prop, descriptor) 方法会直接在一个对象上定义一个新属性,或者修改一个对象的现有属性,并返回此对象。
* descriptor:{
* configurable: 是否可更改描述符类型,默认false
* enumerable:该属性是否会出现在对象的枚举属性中
* value:对应值
* writable:value是否能把被修改,默认false
* }
* defineProperty 与 “=” 差异:
* defineProperty默认不可被枚举、不可被修改
*/
Object.defineProperty(exports, "__esModule", {
value: true
});
// 清空 void 0 === undefined
exports["default"] = void 0;
// 增加对象default属性
// 为什么加default:CommonJS模块没有默认导出,加上方便兼容
var _b = _interopRequireDefault(require("./b.js"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
var a = {
value: 'a',
getB: function getB() {
return _b["default"].value + ' from a.js';
}
};
var _default = a;
exports["default"] = _default;
多个文件打包成一个
1、webpack(一)中格文件生成的对象放在数组中
2、code由字符串变为代码
function(require,module,exports){
{code}
}
3、缓存收集依赖