前言
主要学习一下四种模块加载规范:
- AMD
- CMD
- CommonJS
- ES6 模块
历史
require.js
requirejs 为全局添加了 define 函数,你只要按照这种约定的方式书写这个模块即可。
define(function () { //Do setup work here return { color: "black", size: "unisize" } }); //my/shirt.js now has some dependencies, a cart and inventory //module in the same directory as shirt.js define(["./cart", "./inventory"], function(cart, inventory) { //return an object to define the "my/shirt" module. return { color: "blue", size: "large", addToCart: function() { inventory.decrement(this); cart.add(this); } } } ); 以上示例代码来源于require.js官网
demo代码详见 https://github.com/BillyQin/jsModule/tree/master/requireJs
AMD
require.js 为全局添加了define 函数,按照这种约定方式写即可。
这个约定方式就是AMD(The Asyncchronous Module Definition)
所以AMD规范就是定义了怎么写define函数。只要按照这个规范来写模块和依赖,require.js就能正确解析。
sea.js
demo代码详见 https://github.com/BillyQin/jsModule/tree/master/seaJs
CMD
同样的道理,CMD就是Sea.js对模块定义对规范化产出。
所以CMD的内容就是描述该如何定义模块,如何引入模块,如何导出模块。只要按照这个规范来写模块和依赖,sea.js就能正确解析。
AMD 和 CMD
- AMD 推崇依赖前置,CMD推崇依赖就近
- 对于依赖的模块,AMD 是提前执行,CMD 是延迟执行。
- AMD 是将需要使用的模块先加载完再执行代码
- CMD 是在 require 的时候才去加载模块文件,加载完再接着执行。
CommonJS
AMD 和 CMD 都是用于浏览器的模块规范,而在服务端(node),则采用CommonJS。
CommonJS和sea.js一样,require的时候才去加载模块文件,加载完再接着执行。
demo代码详见 https://github.com/BillyQin/jsModule/tree/master/commonJs
为什么浏览器中不支持 CommonJS 语法呢?
这是因为浏览器环境中并没有 module、 exports、 require 等环境变量。
ES6
es6定义了新的模块加载方案。
// 导出 const addr = 'China' const year = 2018 export { addr, year } // 导入
