最近在使用sea.js。你們知道sea.js遵循CMD規範。該規範的英文說明很簡潔,我試着翻譯了一下,旨在交流。git
Common Module Definition github
通用模塊定義規範瀏覽器
This specification addresses how modules should be written in order to be interoperable in browser-based environment. By implication, this specification defines the minimum features that a module system must provide in order to support interoperable modules.app
本規範規定如何定義和書寫執行在瀏覽器環境中的js模塊,這就是說,本規範定義了一個模塊的最小API,這些API提供與該模塊系統的交互。async
模塊都是單例的。ide
模塊範圍內的自由變量不該該被引入。函數
模塊的執行是按需執行的。ui
Module Definitionthis
A module is defined with define keyword, which is a function.spa
模塊是使用關鍵字「define」定義的一個函數。
define(factory);
factory.define函數接受一個參數,模塊工廠
Factory多是一個函數,或是一個可驗證值
若是factory是一個函數,若是參數指定了,這個函數的前三個參數,按照順序這三個參數是「require」,「exports」,「module」
若是factory不是一個函數,模塊的exports必須設置成一個對象。
Module Context
In a module, there are three free variables: require, exports and module.
模塊中三個變量:require,exports和module
define(function(require, exports, module) {
// The module code goes here
});
The require Function
require是一個函數
require接受一個模塊標識
require返回一個外部模塊對外公開的API
若是請求的模塊沒有返回API,require必須返回null
require.async接受一個模塊標識列表和一個回調函數
回調函數接收第i中指定的做爲參數的模塊列表中的全部模塊的的export做爲函數參數,而且順序和該列表中的模塊順序一致。
若是請求的模塊沒有任何返回,回調函數也必須相應的按照順序接收null。
The exports Object
In a module, there is a free variable called "exports", that is an object that the module may add its API to as it executes.
在模塊中,還有一個參數「exports」,exports是一個對象,包含這個模塊的全部API。
The module Object
The full resolved uri to the module.
模塊的完整可解析的uri
A list of module identifiers that required by the module.
模塊依賴的其餘模塊標識列表
The exported API of the module. It is the same as exports object.
模塊公開的export對象。
Module Identifier
模塊標識必須是合法的字符串
模塊標識不能包含文件擴展名,如.js
模塊標識能夠使用「-」鏈接,如foo-bar
模塊標識能夠使用相對路徑,如 ./foo、../bar
Sample Code
A typical sample
math.js
define(function(require, exports, module) {
exports.add = function() {
var sum = 0, i = 0, args = arguments, l = args.length;
while (i < l) {
sum += args[i++];
}
return sum;
};
});
increment.js
define(function(require, exports, module) {
var add = require('math').add;
exports.increment = function(val) {
return add(val, 1);
};
});
program.js
define(function(require, exports, module) {
var inc = require('increment').increment;
var a = 1;
inc(a); // 2
module.id == "program";
});
Wrapped modules with non-function factory
object-data.js
define({
foo: "bar"
});
array-data.js
define([
'foo',
'bar'
]);
string-data.js
define('foo bar');
------------------------------------------------
來源:
https://github.com/cmdjs/specification/blob/master/draft/module.md
擴展: