CommonJS Modules
CommonJS is a module system used by Node.js. require loads a module, and module.exports determines the value other modules receive.
Know which module system your project runs before mixing syntax from different hosts.
See the mechanism
object Aobject AFollow one example
// article.cjs
module.exports = { title: "Morning" };
// main.cjs — a separate file
const article = require("./article.cjs");
console.log(article.title);These are two separate .cjs files, not a single browser snippet. Save them together and run node main.cjs to print Morning. exports initially refers to module.exports; replacing exports alone does not replace module.exports. Node also supports ESM, with behavior determined by file extension and package configuration. The browser editor does not provide require or a CommonJS module loader.
Predict, change and check
Predict: Would exports = {title: "Night"} replace the value returned by require in the same way as module.exports = ...?
Test your explanation: On a local Node installation, change article.cjs using each assignment form and run the consumer in a fresh process. Keep these files separate.
The tasks below ask you to explain that result and apply the idea to different inputs.
Where to run this example: The two labelled files above belong in a local Node project. The browser’s worker is not a CommonJS host. The separate graded task is an executable model of the aliasing rule.
Apply and distinguish
Keep the loader and the export value distinct
CommonJS provides a module-local scope and exposes module.exports through require. The exports name initially aliases that export object; reassigning exports alone changes the local alias, not the actual export value. A normal require can use the cached exports of an already loaded resolved module.
Use two real .cjs files to test this behavior in Node. Browser workers do not natively provide require or a CommonJS filesystem loader. Node also supports ESM, so a local Node installation does not imply every .js file is necessarily CommonJS; inspect the extension and package configuration.
Check your understanding: State the input contract, identify the operation that changes the result, and give one boundary input that would distinguish the correct rule from the mistake described above.