Differences between CommonJS, AMD, and RequireJS
RequireJS implements AMD APIs.
CommonJS is a way to define a module using an exports object. It defines the content of a module. Simply implement a CommonJS definition as follows:
// 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 makes it clear that you need a require function to obtain dependencies. The exports variable is used to output the module content and some module identifiers used to obtain dependencies. CommonJS has multiple implementations, such as Node. js.
Because the browser is not considered during CommonJS design, it is not suitable for the browser environment (I am not clear about this, but this statement is everywhere, such as the official website of RequireJS ). So we have to do some work to implement asynchronous loading.
On the contrary, RequireJS implements AMD and is designed to adapt to the browser environment. On the surface, AMD began to be a by-product of the CommonJS output format and eventually evolved its own API. The new thing that appears in AMD is the define function, which allows the module to declare its Dependencies before loading the dependencies. For example, the definition may be as follows:
Define ('module/id/string', ['module', 'dependency ', 'array'],
Function (module, factory function ){
Return ModuleContents;
});
Therefore, CommonJS and AMD are different implementations of Apis defined by Javascript modules, but they share the same root cause. AMD is more suitable for browsers because it supports asynchronous loading of module dependencies. RequireJS is an implementation of AMD and retains the spirit of CommonJS as much as possible (mainly on the module identifier ). What's even more confusing is that RequireJS provides a CommonJS package while implementing AMD, so that the CommonJS module can be almost directly introduced by RequireJS.
Define (function (require, exports, module ){
Var someModule = require ('somemodule'); // in the vein of node
Exports. doSomethingElse = function () {return someModule. doSomething () + "bar ";};
});