一、對CommonJS&SeaJS&RequireJS的瞭解
AMD: define + require CMD: exports + require
Amd可以做到避免Common.js的 “臨時讀取並加載文件”,它是提前讀取並加載。
而Cmd可以做到的是,“提前讀取文件,但在需要再加載”,這樣可以避免瀏覽器臨時加載文件的假死,也可以避免提前加載引起的邏輯問題。
都是提前讀取:模塊的加載都是並行的, 沒有區別, 區別在於執行模塊的時機, 或者說是解析。
大家叫sea.js懶加載,也就是 “as lazy as possible”
栗子:來自於:https://www.douban.com/note/283566440/(侵刪)
define(function(require, exports, module) {
console.log('require module: main');
var mod1 = require('./mod1');
mod1.hello();
var mod2 = require('./mod2');
mod2.hello();
return {
hello: function() {
console.log('hello main');
}
};
});
SeaJS的執行結果require module: main
require module: mod1
hello mod1
require module: mod2
hello mod2
hello main
RequireJS的執行結果
require module: mod1
require module: mod2
require module: main
hello mod1
hello mod2
hello main
SeaJS只會在真正需要使用(依賴)模塊時才執行該模塊。
而RequireJS會先儘早地執行(依賴)模塊, 相當於所有的require都被提前了。
二、
就個人來說現在也不怎麼用SeaJS,一般都用webpack做處理
js語言本身並不支持模塊化,如何實現瀏覽器中js模塊化主流有兩種方案:
1. requirejs/seajs: 是一種在線“編譯”模塊的方案,相當於在頁面上加載一個CommonJS/AMD模塊格式解釋器。這樣瀏覽器就認識了define, exports,module這些東西,也就實現了模塊化。
2.browserify/webpack:是一個預編譯模塊打包的方案,相比於第一種方案,這個方案更加智能。由於是預編譯的,不需要在瀏覽器中加載解釋器。你在本地直接寫JS,不管是AMD/CMD/ES6風格的模塊化,它都能認識,並且編譯成瀏覽器認識的JS。注意: browerify打包器本身只支持Commonjs模塊,如果要打包AMD模塊,則需要另外的plugin來實現AMD到CMD的轉換!
ES6: export + import(由於ES6本身是原生語言支持實現的模塊化,但是現代瀏覽器大多都還未支持,因此必須使用相應的transpiler工具轉換成ES5的AMD,CMD模塊,再藉助於systemjs/requirejs等模塊加載工具才能使用。其中ES6的transpiler(代碼轉換器)一般是用babel,他的作用是將ES6)