liveBook · Manning

CommonJS

As explained in The Joy of JavaScript

A server-side JavaScript module specification that defines modules using synchronous loading and the require/module.exports convention.

CommonJS (CJS) is a dynamic JavaScript module system built around programmatic loading and the require/module.exports convention. Dependencies and exposed APIs are resolved while the code runs, so require calls can appear where conditional behavior needs them. section 6.3 section 6.4.3

A CJS module can expose values and functions through exports, while internal variables and helper functions remain private. Consumers receive object values through require; destructuring creates local copies rather than live bindings. section 6.3 section 6.4.3

A configurable calculator module

A calculator module exports feePercent, netTotal, and setFeePercent while keeping precisionRound private. Reassigning a destructured feePercent does not change the module’s value; calling setFeePercent does. section 6.3

Conditional loading

Feature flags can select between compute_balance.js and compute_balance2.js by requiring one module initially and replacing the selected function when a flag is enabled. section 6.4.3

Table 6.1 Loading the Transaction class with different module systems (continued) (view table figure)

System

Type

Example

CommonJS

Dynamic

const Transaction =

require('./domain/Transaction.js');

RequireJS

Dynamic

requirejs(['domain/Transaction.js'], Transaction => {

//... use Transaction
});

ESM

Static

import Transaction from './domain/Transaction.js';

Compare CommonJS’s dynamic require call with RequireJS and ESM import syntax. section 6.3

How The Joy of JavaScript covers it

How deep it goes
Explains dynamic loading, exports, copied destructured values, and conditional selection, while contrasting but not fully detailing ESM internals.
Examples
Uses calculator exports, Transaction loading, validation imports, filesystem imports, and feature-flagged wallet implementations.
What it assumes
Assumes JavaScript functions and objects, while explaining module boundaries, exports, imports, and dynamic loading through examples.
What you can do after
Apply it via Node.js by defining exports, consuming modules with require, and selecting dependencies conditionally.
How it connects
Connects CommonJS with dynamic modules, ECMAScript Modules, RequireJS, AMD, and package-based module loading.

Also explained in

Compare how 3 books explain CommonJS →

Related concepts

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