CommonJS
The CommonJS module proposal specifies a simple API for declaring modules that work outside of the browser (such as on the server). Unlike AMD, it attempts to cover a broader set of concerns such as IO, filesystem, promises, and more.
Originally called ServerJS in a project started by Kevin Dangoor back in 2009, the format was more recently formalized by CommonJS, a volunteer working group that aims to design, prototype, and standardize JavaScript APIs. To date, they’ve attempted to ratify standards for both modules and packages.
Getting Started
From a structure perspective, a CommonJS module is a
reusable piece of JavaScript that exports specific objects made
available to any dependent code. Unlike AMD, there are typically no
function wrappers around such modules (so we won’t see define here, for example).
CommonJS modules basically contain two primary parts: a free
variable named exports, which contains the objects a module wishes to make
available to other modules, and a require function that modules can use to import the exports of other
modules (Examples 11-9, 11-10, and 11-11).
Example 11-9. Understanding CommonJS: require() and exports
// package/lib is a dependency we requirevarlib=require("package/lib");// behaviour for our modulefunctionfoo(){lib.log("hello world!");}// export (expose) foo to other modulesexports.foo=foo;
Example 11-10. Basic consumption of exports
// package/lib is a dependency we requirevarlib=require("package/lib");// behaviour ...