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


