You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
// 独立模块。定义math.js模块
define(function () {
var basicNum = 0;
var add = function (x, y) {
return x + y;
};
return {
add: add,
basicNum :basicNum
};
});
// 非独立模块。定义tool.js模块
define(['m1','m2'], function(m1,m2){
return {
method: function() {
m1.methodA();
m2.methodB();
}
};
});
// 引用模块,将模块放在[]内
require(['math'],function(math){
var sum = math.add(10,20);
});
AMD特点
异步加载模块。模块的加载不会影响后面语句的执行。(加载完成,会执行回调函数)
编译时执行
依赖前置,define的时候就引入
require.js包裹CommonJS
define(function (require, exports, module){
var someModule = require("someModule");
var anotherModule = require("anotherModule");
someModule.doTehAwesome();
anotherModule.doMoarAwesome();
exports.asplode = function (){
someModule.doTehAwesome();
anotherModule.doMoarAwesome();
};
});
CMD
CMD全称Common Module Definition,由国内玉伯大神在开发SeaJS时提出。
CMD示例:
//m1.js
define(function(require, exports, module) {
var a = require('./a');
a.doSomething();
var b = require('./b');
b.doSomething();
})
seajs.use(['m1'],function(m1){
})
CMD特点
对于依赖的模块,CMD 是延迟执行。不过 RequireJS 从 2.0 开始,也改成可以延迟执行(根据写法不同,处理方式不同)。CMD 推崇 as lazy as possible.
// if the module has no dependencies, the above pattern can be simplified to
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define([], factory);
} else if (typeof exports === 'object') {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
module.exports = factory();
} else {
// Browser globals (root is window)
root.returnExports = factory();
}
}(this, function () {
// Just return a value to define the module export.
// This example returns an object, but the module
// can return a function as the exported value.
return {};
}));
前言
CommonJS
CommonJS
示例:CommonJS
特点CommonJS
循环加载上述三个文件中,
a.js
加载了b.js
,而b.js
又加载了a.js
。此时返回a.js
不完整的版本。执行结果如下:如果此时将
main.js
修改如下:此时的执行结果是:
有上述执行结果的原因为由于
CommonJS
在多次加载的时候,会直接从缓存读取exports
属性,所以a.js
和b.js
内部的console
不会执行。AMD
AMD
示例AMD
特点require.js
包裹CommonJS
CMD
UMD
exports
是否存在),存在则使用Node.js模块格式(CommonJS
)define
是否存在),存在则使用AMD方式加载模块。window
或global
)ES6 Module
TreeShaking
正是利用此特点实现。当然import()
也支持动态加载,返回一个Promise
参考
The text was updated successfully, but these errors were encountered: