// model1.js
define(function (require, exports, module) {
console.log(‘model1 entry’);
exports.getHello = function () {
return ‘model1’;
}
});
// model2.js
define(function (require, exports, module) {
console.log(‘model2 entry’);
exports.getHello = function () {
return ‘model2’;
}
});
// main.js
define(function(require, exports, module) {
var model1 = require(‘./model1’); //在需要时申明
console.log(model1.getHello());
var model2 = require(‘./model2’); //在需要时申明
console.log(model2.getHello());
});
// 输出
// model1 entry
// model1
// model2 entry
// model2
https://github.com/hua1995116/packaging-example/tree/master/modules-introduction/CMD
总结: 对比和 AMD 的写法就可以看出 AMD 和 CMD 的区别。虽然现在 CMD 已经凉了。但是 CMD 更加接近于 CommonJS 的写法,但是 AMD 更加接近于浏览器的异步的执行方式。
UMD
UMD文档[4]
UMD(Universal Module Definition - 通用模块定义)模式,该模式主要用来解决CommonJS模式和AMD模式代码不能通用的问题,并同时还支持老式的全局变量规范。
示例展示
// bundle.js
(function (global, factory) {
typeof exports === ‘object’ && typeof module !== ‘undefined’ ? module.exports = factory() :
typeof define === ‘function’ && define.amd ? define(factory) :
(global = global || self, global.myBundle = factory());
}(this, (function () { ‘use strict’;
var main = () => {
return ‘hello world’;
};
return main;
})));
// index.html
1.判断define为
函数,并且是否存在define.amd
,来判断是否为AMD规范,2.判断module
是否为一个对象,并且是否存在module.exports
来判断是否为CommonJS
规范3.如果以上两种都没有,设定为原始的代码规范。
代码地址:https://github.com/hua1995116/packaging-example/tree/master/modules-introduction/UMD
ES Modules
ES Modules 文档[5]
ES modules(ESM)是 JavaScript 官方的标准化模块系统。
1.它因为是标准,所以未来很多浏览器会支持,可以很方便的在浏览器中使用。(浏览器默认加载不能省略.js)2.它同时兼容在node环境下运行。3.模块的导入导出,通过import
和export
来确定。可以和Commonjs模块混合使用。4.ES modules 输出的是值的引用,输出接口动态绑定,而 CommonJS 输出的是值的拷贝5.ES modules 模块编译时执行