CommonJS,AMD,RequireJS的差別

來源:互聯網
上載者:User

標籤:cti   node   art   rip   實現   define   array   javascrip   它的   


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的差別

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.