CommonJs 定義的是同步模塊加載方案,AMD/CMD定義的是異步模塊加載方案git
CommonJs: 包含兩大工具 require() 以及 module.exportsgithub
module.exports 用於產生一個模塊,方法是將在文件末尾加入 module.exports = 該文件內的一個變量,就使得該變量成爲模塊異步
require 用於引用一個模塊,例如 require("./helllo") 括號內爲路徑名而且不要".js"的後綴async
//舉例 // moduleA.js module.exports = function( value ){ return value*2; } // moduleB.js var multiplyBy2 = require('./moduleA'); var result = multiplyBy2( 4 );
AMD RequireJS 在推廣過程當中對模塊定義的規範化產出 函數
- define(id?, dependencies?, factory); 工具
- id 可選參數,字符串類型。獨一無二,id即爲模塊的id.若是id參數存在,那麼id參數必須是頂層或者絕對id(而不是相對id)ui
- dependencies 可選參數,id列表,用於指出該模塊的依賴模塊,依賴模塊的id多是相對id。若是dependencies參數不存在,模塊加載器有可能掃描factory函數來得到相關的依賴模塊。當模塊加載器加載該模塊時,會先加載依賴模塊spa
- factory 必要參數,函數類型或者object類型。若爲函數類型,該函數只能被執行一次,若爲object類型,則應該做爲模塊的輸出code
Sets up the module with ID of "alpha", that uses require, exports and the module with ID of "beta":blog
define("alpha", ["require", "exports", "beta"], function (require, exports, beta) { exports.verb = function() { return beta.verb(); //Or: return require("beta").verb(); } });
An anonymous module that returns an object literal:
define(["alpha"], function (alpha) {
return {
verb: function(){
return alpha.verb() + 2;
}
};
});
A dependency-free module can define a direct object literal:
define({
add: function(x, y){
return x + y;
}
});
加載方法
require(['math'], function (math){
alert(math.add(1,1));
});
CMD CMD定義規範中一個模塊就是一個文件。代碼書寫格式:
更多請看: https://github.com/seajs/seajs/issues/242
define(id?, deps?, factory)
require(id)
require.async(id, callback?)
require.resolve(id)