RequireJS implements the AMD API (source) .
(RequireJS实现AMD API (源) 。)
CommonJS is a way of defining modules with the help of an exports
object, that defines the module contents.
(CommonJS是在exports
对象的帮助下定义模块的方法,该对象定义了模块的内容。)
Simply put, a CommonJS implementation might work like this:(简而言之,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"; };
Basically, CommonJS specifies that you need to have a require()
function to fetch dependencies, an exports
variable to export module contents and a module identifier (which describes the location of the module in question in relation to this module) that is used to require the dependencies ( source ).
(基本上,CommonJS指定您需要有一个require()
函数来获取依赖项,一个exports
变量以导出模块内容以及一个用来标识要求的模块标识符(描述了该模块相对于该模块的位置)依赖项( 源 )。)
CommonJS has various implementations, including Node.js , which you mentioned.(CommonJS具有各种实现,包括您提到的Node.js。)
CommonJS was not particularly designed with browsers in mind, so it doesn't fit in the browser environment very well ( I really have no source for this--it just says so everywhere, including the RequireJS site. ) Apparently, this has something to do with asynchronous loading, etc.
(CommonJS并不是专门为浏览器而设计的,因此它不太适合浏览器环境( 我确实没有相关资源-它在包括RequireJS网站在内的所有地方都这么说。 )显然,这有一些不足之处异步加载等)
On the other hand, RequireJS implements AMD, which is designed to suit the browser environment ( source ).
(另一方面,RequireJS实现了AMD,该AMD旨在适应浏览器环境( source )。)
Apparently, AMD started as a spinoff of the CommonJS Transport format and evolved into its own module definition API.(显然,AMD最初是从CommonJS Transport格式衍生出来的,后来演变为自己的模块定义API。)
Hence the similarities between the two.(因此,两者之间的相似之处。)
The new feature in AMD is the define()
function that allows the module to declare its dependencies before being loaded.(AMD中的新功能是define()
函数,该函数允许模块在加载之前声明其依赖性。)
For example, the definition could be:(例如,定义可以是:)
define('module/id/string', ['module', 'dependency', 'array'],
function(module, factory function) {
return ModuleContents;
});
So, CommonJS and AMD are JavaScript module definition APIs that have different implementations, but both come from the same origins.
(因此,CommonJS和AMD是JavaScript模块定义API,它们具有不同的实现,但是它们来自相同的来源。)
To confuse you even more, RequireJS, while being an AMD implementation, offers a CommonJS wrapper so CommonJS modules can almost directly be imported for use with RequireJS.
(更令人困惑的是,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"; };
});
I hope this helps to clarify things!
(我希望这有助于澄清问题!)