CommonJS
和AMD
是对JavaScript
模块化的两种标准
RequireJS
RequireJS实现了AMDAPI,它是AMD
的一个实现,但同时又想保持CommonJS
的一些特点。
CommonJS
CommonJS是通过exports
对象来定义模块的一种方式,通常像下面这样:
// someModule.js
exports.doSomething = function() { return "foo"; };
//otherModule.js
var someModule = require('someModule'); // in the vein of node
exports.doSomethingElse = function() { return someModule.doSomething() + "bar"; };
一般来说,CommonJS
指明你需要用require()
函数来获取依赖,一个exports
对象来输出模块内容。CommonJS
有许多中实现,包括Node.js
。CommonJS
并不是为了浏览器而设计的,所以它在浏览器中可能会出现一些问题。
另一方面,RequireJS实现了AMDAPI,专门为浏览器做了适配。AMD中一些新的特性就是通过define()
来允许模块提前定义它的依赖:
define('module/id/string', ['module', 'dependency', 'array'],
function(module, factory function) {
return ModuleContents;
});
CommonJS
和AMD
是JavaScript
的模块定义API,有不同的实现。CommonJS
通常被用在服务器端。
AMD
AMD
更加适合浏览器,因为它可以异步加载模块