Relation between CommonJS, AMD and RequireJS?

gremo picture gremo · May 13, 2013 · Viewed 178.6k times · Source

I'm still very confused about CommonJS, AMD and RequireJS, even after reading a lot.

I know that CommonJS (formerly ServerJS) is a group for defining some JavaScript specifications (i.e. modules) when the language is used outside the browser. CommonJS modules specification has some implementation like Node.js or RingoJS, right?

What's the relation between CommonJS, Asynchronous Module Definition (AMD) and RequireJS?

Is RequireJS an implementation of the CommonJS module definition? If yes, what's AMD then?

Answer

jakee picture jakee · May 13, 2013

RequireJS implements the AMD API (source).

CommonJS is a way of defining modules with the help of an exports object, that defines the module contents. Simply put, a CommonJS implementation might work like this:

// 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 has various implementations, including Node.js, which you mentioned.

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.