ECMAScript modules and CommonJS
How it works
CommonJS is a host module convention used by Node.js. A .cjs file exposes a value through module.exports; require() loads an available CommonJS module synchronously. An .mjs file uses ECMAScript imports and exports. Node supports interoperability, but the details depend on version and module type; do not assume a named CommonJS export is always discoverable from ESM. Browsers do not natively provide Node’s require.
Example 1
Save each file separately. Run with Node.js: main.cjs. This is a multi-file example, not a single editor snippet.
calc.cjs
main.cjs
Expected output in the tested environment:
12The exported function is returned by Node’s require.
Common mistake
Assigning exports = newValue does not replace module.exports in ordinary CommonJS. Use module.exports for replacement.
Practice
Rewrite both files as .mjs using a default export and an import. Compare the observable result.
Run this practice in the documented local environment. ByteMind module and asynchronous grader support is not yet verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
ECMAScript modules and CommonJS — Knowledge Check
Reason about the concept and predict its behavior in the indicated environment.
What does module.exports designate in CommonJS?
Which extension explicitly identifies a Node CommonJS file?
Why avoid relying on inferred CommonJS named exports in portable ESM interop?
Is Node require() a browser-standard ECMAScript function?
For ECMAScript modules and CommonJS, what is the console output of example 1 in Node.js 22.16.0?
// File: calc.cjsmodule.exports = n => n * 4;
// File: main.cjsconst multiply = require("./calc.cjs");console.log(multiply(3));