最近在使用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
扩展: