CommonJSAMD是对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.jsCommonJS并不是为了浏览器而设计的,所以它在浏览器中可能会出现一些问题。

另一方面,RequireJS实现了AMDAPI,专门为浏览器做了适配。AMD中一些新的特性就是通过define()来允许模块提前定义它的依赖:

define('module/id/string', ['module', 'dependency', 'array'], 
function(module, factory function) {
  return ModuleContents;  
});

CommonJSAMDJavaScript的模块定义API,有不同的实现。CommonJS通常被用在服务器端。

AMD

AMD更加适合浏览器,因为它可以异步加载模块

results matching ""

    No results matching ""