CommonJS (CJS)

Dec 01, 2020javascriptjs-modules

CommonJS (CJS) is an ambitious project started by Kevin Dangoor back in 2009 in an attempt to bring JavaScript to the outside of web browsers, originally called ServerJS. The intend is to define a set of APIs that are useful both for non-web JavaScript implementations, with standardized package names to provide interoperability within the ecosystem.

CJS APIs define a Javascript module format in which you can export an object in some modules and require synchronously in other modules.

1. In a module, there is a free variable "require", that is a function.
  1. The "require" function accepts a module identifier.
  2. "require" returns the exported API of the foreign module.
  3. If there is a dependency cycle, the foreign module may not have finished executing at the time it is required by one of its transitive dependencies; in this case, the object returned by "require" must contain at least the exports that the foreign module has prepared before the call to require that led to the current module's execution.
  4. If the requested module cannot be returned, "require" must throw an error.
2. In a module, there is a free variable called "exports", that is an object that the module may add its API to as it executes.
3. modules must use the "exports" object as the only means of exporting.

CJS 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

// utils.js
const log = (message) => {
  console.log(message)
}
module.exports = {log}
// index.js
const utils = require('./utils')
utils.log('Hello World')

The require() is a synchronous call, it is expected to return the module immediately. This design works fine in a local environment like Node.js, but they did not fully embrace network loading and inherent asynchronicity in the browser.