RequireJS 实现了 AMD API (source)。
CommonJS 是一种在exports 对象的帮助下定义模块的方法,该对象定义了模块内容。简单地说,CommonJS 实现可能是这样工作的:
// 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 变量来导出模块内容和一个模块标识符(它描述了与该模块相关的模块的位置)用于要求依赖项(source)。 CommonJS 有各种实现,包括你提到的 Node.js。
CommonJS 在设计时并没有特别考虑浏览器,所以它不太适合浏览器环境(*我真的没有这方面的来源——它只是到处都这么说,包括the RequireJS site.*)显然,这个与异步加载等有关。
另一方面,RequireJS 实现了 AMD,它旨在适应浏览器环境 (source)。显然,AMD 最初是从 CommonJS 传输格式衍生出来的,并演变成自己的模块定义 API。因此,两者之间的相似之处。 AMD 的新功能是define() 函数,它允许模块在加载之前声明其依赖项。例如,定义可以是:
define('module/id/string', ['module', 'dependency', 'array'],
function(module, factory function) {
return ModuleContents;
});
因此,CommonJS 和 AMD 是 JavaScript 模块定义 API,它们具有不同的实现,但都来自相同的起源。
-
AMD 更适合浏览器,因为它支持模块依赖的异步加载。
-
RequireJS 是 AMD 的实现,同时试图保持 CommonJS 的精神(主要在模块标识符中)。李>
更让你困惑的是,RequireJS 虽然是 AMD 的实现,但提供了一个 CommonJS 包装器,因此几乎可以直接导入 CommonJS 模块以与 RequireJS 一起使用。
define(function(require, exports, module) {
var someModule = require('someModule'); // in the vein of node
exports.doSomethingElse = function() { return someModule.doSomething() + "bar"; };
});