1. 程式人生 > >RequireJS中建立模組的幾種方式

RequireJS中建立模組的幾種方式

模組不同於傳統的指令碼檔案,它良好地定義了一個作用域來避免全域性名稱空間汙染。它可以顯示地列出其依賴關係,並以函式(定義此模組的那個函式)引數的形式將這些依賴進行注入,而無需引用全域性變數。RequireJS的模組是模組模式的一個擴充套件,其好處是無需全域性地引用其他模組。
RequireJS的模組語法允許它儘快地載入多個模組,雖然載入的順序不定,但依賴的順序最終是正確的。同時因為無需建立全域性變數,甚至可以做到在同一個頁面上載入同一模組的不同版本。

簡單的值對

如果一個模組僅含值對,沒有任何依賴,則再define()中定義這些值對就好了:

//Inside file my/shirt.js
: define({ color: "black", size: "unisize" });

函式式定義

如果一個模組沒有任何依賴,但需要一個做setup工作的函式,則再define()中定義該函式,並將其傳給define():

//my/shirt.js now does setup work
//before returning its module definition.
define(function () {
//Do setup work here
return {
color: "black",
size: "unisize"
}
});

存在依賴的函式式定義

如果模組存在依賴:則第一個引數時依賴的名稱陣列;第二個引數時函式,在模組的所有依賴載入完畢後,該函式會被呼叫來定義該模組,因此該模組應該返回一個定義了本模組的object。依賴關係會以引數的形式注入到該函式上,引數列表與依賴名稱列表一一對應。

//my/shirt.js now has some dependencies, a cart and inventory
//module in the same directory as shirt.js
define(["./cart", "./inventory"], function(cart, inventory) {
//return an object to define the "my/shirt" module.
return {
color: "blue",
size: "large",
addToCart: function() {
inventory.decrement(this);
cart.add(this);
}
}
}
);

將模組定義為一個函式

對模組的返回值型別並沒有強制為一定是個object,任何函式的返回值都是允許的。此處是一個反悔了函式的模組定義:

//A module definition inside foo/title.js. It uses
//my/cart and my/inventory modules from before,
//but since foo/title.js is in a different directory than
//the "my" modules, it uses the "my" in the module dependency
//name to find them. The "my" part of the name can be mapped
//to any directory, but by default, it is assumed to be a
//sibling to the "foo" directory.
define(["my/cart", "my/inventory"],
function(cart, inventory) {
//return a function to define "foo/title".
//It gets or sets the window title.
return function(title) {
return title ? (window.title = title) :
inventory.storeName + ' ' + cart.name;
}
}
);

簡單包裝CommonJS來定義模組

如果你現有一些以CommonJS模組格式編寫的程式碼,而這些程式碼難於使用上述依賴名稱陣列引數的形式來重構,你可以考慮直接將這些依賴對應到一些本地變數中進行使用。你可以使用一個CommonJS的簡單包住幾個你來實現:

define(function(require, exports, module) {
var a = require('a'),
b = require('b');
//Return the module value
return function () {};
}
);

定義一個命名模組

你可能會看到一些define()中包含了一個模組名稱作為首個引數:

//Explicitly defines the "foo/title" module:
define("foo/title",
["my/cart", "my/inventory"],
function(cart, inventory) {
//Define foo/title object in here.
}
);