標籤:
RequireJS實現了AMD的API.
CommonJS是使用exports對象來定義模組的一種方法,它定義了模組的內容。簡單地實現一個CommonJS的定義就像下面這樣:
// someModule.js
exports.doSomething = function() { return "foo"; };
//otherModule.js
var someModule = require(‘someModule‘); // in the vein of node
exports.doSomethingElse = function() { return someModule.doSomething() + "bar"; };
基本上CommonJS明確了你需要有一個require函數來擷取依賴,exports變數來輸出模組的內容和一些用來擷取依賴的模組標識符。CommonJS有多種實現,比如Node.js.
因為CommonJS設計的時候沒有考慮瀏覽器,所以它不適合瀏覽器環境(我其實對這個不明確,但是這種說法到處都有,比如RequireJS官網)。所以我們得做一些工作來實現非同步載入。
相反,RequireJS實現了AMD,它被設計用來適應瀏覽器環境。表面上看來,AMD開始是CommonJS輸出格式的副產品,而且最終進化出了自己的API。在AMD中出現的新東西是define函數,它允許模組在載入依賴之前聲明它的依賴。例如定義可能就像下面這樣:
define(‘module/id/string‘, [‘module‘, ‘dependency‘, ‘array‘],
function(module, factory function) {
return ModuleContents;
});
因此CommonJS和AMD是JavaScript模組定義API的不同的實現,但是他們有相同的根源。AMD更適合瀏覽器,因為它支援非同步載入模組依賴。RequireJS是AMD的一個實現,而且盡量保留了CommonJS的精神(主要是模組標識符上)。更讓人混亂的是,RequireJS在實現AMD的同時,還提供了一個CommonJS包裹,這樣CommonJS模組可以幾乎直接被RequireJS引入。
define(function(require, exports, module) {
var someModule = require(‘someModule‘); // in the vein of node
exports.doSomethingElse = function() { return someModule.doSomething() + "bar"; };
});
CommonJS,AMD,RequireJS的區別