liveBook · Manning

CommonJS

As explained in Secrets of the JavaScript Ninja, Third Edition

CommonJS is a JavaScript module-system specification traditionally based on synchronous require calls and module.exports assignments.

CommonJS is a JavaScript module system built around synchronous `require()` calls and exports attached to `module.exports` (also available as `exports`). It grew as a practical way to modularize JavaScript outside the browser, using familiar JavaScript concepts rather than new syntax. section 13.2

Its design has practical tradeoffs, especially when modules meet ESM:

  • `require()` is dynamic: it can appear inside functions or conditionals and can use a runtime-built argument. CommonJS loading is synchronous. section 13.2.2
  • CommonJS packages have been bundled for browser use. ESM can generally consume CommonJS, but loading ESM from CommonJS is trickier; exports are represented as one object, with the default export accessed through `.default`. section 13.0 section 13.4
  • A CommonJS module cannot load an ESM module that uses top-level `await` with `require()`; ESM can consume CommonJS while using top-level `await`. section 13.2.2
// Require 1.js, 2.js, or 3.js at random
require(`./${Math.ceil(Math.random() * 3)}.js`);

A runtime-built path illustrates how `require()` can select a module dynamically. section 13.2.2

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Explains module exports, dynamic synchronous loading, and ESM interoperability limits.
Examples
Uses a runtime-built `require()` path to demonstrate dynamic module selection.
What you can do after
Understand how dynamic synchronous loading affects CommonJS interoperability with ESM, especially for top-level await.
How it connects
Connects CommonJS to ECMAScript modules, bundlers, and top-level await.

Also explained in

Compare how 5 books explain CommonJS →

Related concepts

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