RequireJS 是什麼
RequireJS 由 James Burke 建立,而他也是 AMD 規範的推手。它把 JavaScript 的組織方式整個翻過來:你不再用一串 <script> 標籤把檔案依序塞進 HTML,也不用靠標籤的先後順序去維護相依關係。
壓縮後僅約 14K 的它,是 AMD 規範最經典的實作之一,也能與其他框架並存。以下整理實際使用時最容易踩到的幾個細節。
1. 函式式定義(帶相依)
第一個參數是相依模組的名稱陣列,第二個參數是函式;等到所有相依都載入完成,這個函式才會被呼叫來定義本模組,因此通常要回傳一個物件。相依會以參數形式注入,順序與名稱陣列一一對應。
define(['a'], function(aJ) {
var hello = function(){
aJ.hello('i am c.js');
}
return { hello : hello }
});
回傳值並不強制是物件,任何型別都可以。
2. CommonJS 模組格式
這種寫法用到三個參數:require 負責載入相依、exports 用來導出變數或方法、module 則是模組自身的資訊。
require.config({
baseUrl: "",
config: { 'b': { size: 'large' } },
paths: { a : 'base/a', b : 'base/b', c : 'base/c' }
});
define(function(require, exports, module) {
var aJ = require("a");
var hello = function(){ aJ.hello('i am b.js'); }
var hello2 = function(){ aJ.hello('i am b.js22'); }
exports.hello = hello;
console.log("b.js : exports", exports);
console.log("b.js : module", module);
console.log("b.js : config", module.config());
// return 會覆蓋前面的 exports,兩者不能併用
/* return { hello : hello2 } */
});
印出來可以觀察到:exports 其實是 module 的一個屬性;module 裡含別名、uri、導出物件與 config 方法;而 module.config() 正是把 application 層級設定往下傳給模組的管道,設定來源是 requirejs.config() 裡的 config 項目。
RequireJS 第一次載入之後會走快取,之後的 require 拿到的都是同一份。因此模組內定義的變數會被所有呼叫端共用。
define(function() {
var index = 0;
var hello = function(msg){ console.log(msg); }
var addIndex = function(){ index++; }
var getIndex = function(){ return index; }
return { hello : hello, addIndex : addIndex, getIndex : getIndex }
});
require(['a'], function (A) {
require(['a'], function (A) {
console.log(A.getIndex()); // 0
A.addIndex();
A.addIndex();
});
require(['a'], function (A) {
console.log(A.getIndex()); // 2,因為共用同一份實例
});
});
如果業務上需要各自獨立的狀態,就得把狀態放到函式回傳的物件裡,或改用工廠函式產生新實例,別直接把計數器攤在模組頂層。
快取在正式環境很好用,開發途中卻很惱人。可以在 config 加上 urlArgs,讓每次請求的網址帶一段變動的查詢參數:
urlArgs: "bust=" + (new Date()).getTime()
記得部署到正式環境前把它移除,否則快取機制就等於關掉了。
RequireJS 支援 CommonJS 的 package 結構,但要額外配置。packages 裡每個項目有三個屬性:name(套件名,用於模組名前綴)、location(相對 baseUrl 的實體路徑,除非以 / 開頭或含通訊協定)、main(以套件名 require 時要載入的入口模組,預設為 main,路徑相對於套件目錄)。
// main.js
require.config({
baseUrl: "",
packages: [
{ name: "student", location: "package-stu" },
{ name: "teacher", location: "package-tea" }
],
urlArgs: "bust=" + (new Date()).getTime()
});
require(["student/store", "teacher/tea"], function (Sto, Tea) {
Sto.hello();
Tea.hello();
});
// tea.js
define(function(require, exports, module) {
exports.hello = function(){ console.log('i am a teacher.'); }
});
// stu.js
define(function(require, exports, module) {
exports.name = '海角';
});
// store.js
define(function(require, exports, module) {
var stu = require("student/stu");
exports.hello = function(){ console.log('i am ' + stu.name); }
});
這種跨套件寫法有兩處讓我覺得不太順:一是套件內模組引用其他模組的寫法,反而會影響使用端的模組風格;二是套件裡的 main 入口似乎可有可無,即使留空也不影響運行。實際專案若要把這套結構用得一致,最好在團隊內先定好慣例。