Relation between CommonJS, AMD and RequireJS?
Introduction
Both CommonJS and AMD are JavaScript module definition APIs that have different implementations.
RequireJS implements the AMD API.
CommonJS is a way of defining modules with the help of an exports
object, that defines the module contents. An implemention is in Node.js.
More details
RequireJS
RequireJS implements AMD, which is designed to suit the browser environment. Apparently AMD started as an offspin of CommonJS Transport format and evolved into its own module definition API. Hence the similiarities between the two. The new thing in AMD is the define()
function that allows the module to declare its dependencies before being loaded. For example the definition could be:
define('module/id/string', ['module', 'dependency', 'array'],
function(module, factory function) {
return ModuleContents;
});
RequireJS, while being an AMD implementation, offers a CommonJS wrapper so CommonJS modules can almost directly be imported into use with RequireJS.
define(function(require, exports, module) {
var someModule = require('someModule'); // in the vein of node
exports.doSomethingElse = function() { return someModule.doSomething() + "bar"; };
});
CommonJS
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 the require()
function to fetch dependencies, the exports
variable to export module contents and some module identifier (that describes the location of the module in question in relation to this module) that is used to require the dependencies. CommonJS has various implementations, for example Node.js.
CommonJS was not particularly designed with browsers in mind, so it doesn't fit to the browser environment very well. Apparently this has something to do with asynchronous loading etc.
Reference
Latest Post
- Dependency injection
- Directives and Pipes
- Data binding
- HTTP Get vs. Post
- Node.js is everywhere
- MongoDB root user
- Combine JavaScript and CSS
- Inline Small JavaScript and CSS
- Minify JavaScript and CSS
- Defer Parsing of JavaScript
- Prefer Async Script Loading
- Components, Bootstrap and DOM
- What is HEAD in git?
- Show the changes in Git.
- What is AngularJS 2?
- Confidence Interval for a Population Mean
- Accuracy vs. Precision
- Sampling Distribution
- Working with the Normal Distribution
- Standardized score - Z score
- Percentile
- Evaluating the Normal Distribution
- What is Nodejs? Advantages and disadvantage?
- How do I debug Nodejs applications?
- Sync directory search using fs.readdirSync