liveBook · Manning

CommonJS

As explained in Secrets of the JavaScript Ninja, Second Edition

A JavaScript module system that defines reusable modules with synchronous loading, commonly used in Node.js.

As an application grows, a single tangle of code becomes harder to maintain, and global names are more likely to collide. CommonJS is a module standard for splitting JavaScript into reusable pieces with defined public interfaces. It is especially suited to server-side JavaScript, including Node.js. section 11.0 section 11.1.2

The basic pattern is short:

  • Use require("jQuery") to obtain a dependency. section 11.1.2
  • Assign an object to module.exports to define what other modules can use. Keep implementation details, such as a click counter and its handler, out of that public interface. section 11.1.2 section 11.1
  • Load the module with require("MouseCounterModule.js"), then call its exported countClicks method. section 11.1.2
Listing 11.4. Using CommonJS to define a module
//MouseCounterModule.js
const $ = require("jQuery");                      #A
let numClicks = 0; 
const handleClick = () => {
  alert(++numClicks);
};

module.exports = {                                #B
  countClicks: () => {
    $(document).on("click", handleClick);
  }
};

The click-counter listing puts the dependency at the top and the public interface in module.exports. Compare those two lines with the counter and handler that support the interface. section 11.1.2

Choose the loading model with the runtime in mind. CommonJS loads modules synchronously, making it more appropriate for servers; AMD was designed for browsers and loads dependencies asynchronously to avoid blocking. ES6 modules offer another approach, with import and export syntax. section 11.1.2 section 11.3

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Shows module definition and consumption through require and module.exports, but leaves project setup beyond scope.
Examples
Uses a jQuery-dependent click-counter module and a require call that invokes its exported method.
What it assumes
Assumes familiarity with JavaScript functions and objects while building on modules as a way to organize code.
What you can do after
Build it from scratch using require for dependencies and module.exports for a public interface.
How it connects
Contrasts synchronous loading with AMD’s asynchronous loading and relates CommonJS syntax to ES6 modules.

Also explained in

Compare how 3 books explain CommonJS →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Second Edition. The section links point to the parts of the book it draws on.