CommonJS vs ESM in Node.js: Modules Tutorial with Runnable Examples

Learn how Node.js classifies CommonJS and ESM files, run both module formats, fix loader errors, and migrate across explicit boundaries.

KnowledgeGate Team

Exam prep & CS education

Updated 11 Nov 20265 min read
CommonJS vs ESM in Node.js: Modules Tutorial with Runnable Examples

One Node.js file uses require, another uses import, and code copied between them throws loader errors even though both files are JavaScript. CommonJS and ESM are two module contracts, not two languages: each defines how a file exposes values, loads dependencies, and behaves at runtime. The same invoice calculation runs in both formats, produces 1475, and exposes predictable loader errors and format trade-offs.

CommonJS and ESM: the mental model before syntax

A module is a scoped file with a public interface. CommonJS exposes values through module.exports and loads them with require(). ESM uses export and import.

Question

CommonJS

ESM

Marker syntax

module.exports / require

export / import

Explicit extensions

.cjs

.mjs

Common .js control

"type": "commonjs"

"type": "module"

Loading style

Synchronous require()

Statically declared imports, with asynchronous features such as top-level await

Local relative paths

Resolution conveniences

Explicit file extensions in imports

The Node.js Packages documentation defines these rules. Packages can mix formats at explicit boundaries. Modules in JavaScript: Import, Export, and Runnable Examples develops ESM syntax, browser loading, dynamic import, and live bindings through cart and counter examples. The Node.js decision is narrower: contrast ESM live bindings with CommonJS caching, then test format detection, interop, and migration boundaries. For broader programming and web-development study, see Coding & Skill Development Courses.

Run the same invoice module in CommonJS and ESM

Create this exact tree:

Code
module-lab/
|-- commonjs/
|   |-- invoice.cjs
|   `-- app.cjs
`-- esm/
    |-- invoice.mjs
    `-- app.mjs

Put this in commonjs/invoice.cjs:

js
function invoiceTotal(subtotal, taxRate) {
  return subtotal + subtotal * taxRate;
}
module.exports = { invoiceTotal };

Then create commonjs/app.cjs:

js
const { invoiceTotal } = require('./invoice.cjs');
const subtotal = 1250;
const taxRate = 0.18;
console.log(invoiceTotal(subtotal, taxRate));

node commonjs/app.cjs prints 1475: tax is 1250 x 0.18 = 225, then total is 1250 + 225 = 1475.

In esm/invoice.mjs, only the boundary syntax changes:

js
export function invoiceTotal(subtotal, taxRate) {
  return subtotal + subtotal * taxRate;
}

Create esm/app.mjs:

js
import { invoiceTotal } from './invoice.mjs';
const subtotal = 1250;
const taxRate = 0.18;
console.log(invoiceTotal(subtotal, taxRate));

node esm/app.mjs also prints 1475. Trace export, load, call with 1250 and 0.18, then output.

Side-by-side module-flow figure comparing CommonJS and ESM invoice calculations: both start at 1,250 with an 18% tax, compute 225, and print 1,475.

How Node.js decides whether a file is CommonJS or ESM

Node treats .cjs as CommonJS and .mjs as ESM. A .js file follows the nearest package.json: "type": "module" selects ESM and "type": "commonjs" selects CommonJS. Without a marker, Node.js can inspect syntax to detect ESM. Set type to remove ambiguity.

Copy the ESM files into explicit-esm/ as invoice.js and app.js, change the import to ./invoice.js, and add:

json
{ "type": "module" }

node explicit-esm/app.js prints 1475. Copy the CommonJS files into explicit-cjs/ as .js, add { "type": "commonjs" }, and require ./invoice.js. node explicit-cjs/app.js prints 1475.

ESM local imports require the extension. from './invoice' produces ERR_MODULE_NOT_FOUND; restore ./invoice.mjs. This does not apply to node:path or installed package names.

Node.js module-format decision tree showing .mjs as ESM, .cjs as CommonJS, and ESM local imports requiring extensions, with ./invoice ending in ERR_MODULE_NOT_FOUND.

The behavioural differences syntax conversion can hide

CommonJS caches a module after its first resolved load. In counter.cjs:

js
let loads = 0;
loads += 1;
module.exports = { loads };

In cache-demo.cjs:

js
const first = require('./counter.cjs');
const second = require('./counter.cjs');
console.log(first.loads, second.loads, first === second);

The output is 1 1 true. The resolved module executed once, and both calls received its cached exported object, as the Node.js CommonJS modules documentation explains.

ESM imports are live bindings, not copied values. Put this in counter.mjs:

js
export let count = 1;
export function increment() { count += 1; }

In live-demo.mjs:

js
import { count, increment } from './counter.mjs';
console.log(count);
increment();
console.log(count);

It prints 1 and then 2: the imported binding reflects the exporter's update.

ESM also permits top-level await:

js
const value = await Promise.resolve(7);
console.log(value);

await-demo.mjs prints 7. In CommonJS, use an async function or dynamic import(). The Node.js ESM documentation defines this boundary.

Interoperability and a safe migration path

ESM can consume CommonJS through a default import:

js
// legacy.cjs
module.exports = { triple(number) { return number * 3; } };

// consume-legacy.mjs
import legacy from './legacy.cjs';
console.log(legacy.triple(14));

This prints 42. Node exposes module.exports as the default export. Do not assume its properties are reliable named exports.

For the broadly useful asynchronous bridge in the other direction:

js
// modern.mjs
export function triple(number) { return number * 3; }

// consume-modern.cjs
import('./modern.mjs').then(({ triple }) => console.log(triple(14)));

This prints 42. Current Node.js can require() synchronous ESM under documented conditions, so the word never is outdated. An ESM graph with top-level await needs asynchronous loading. This is version-sensitive, so check the official CommonJS and ESM documentation.

Migrate in four controlled steps:

  1. Add or confirm tests.

  2. Choose an explicit boundary with extensions or package.json type.

  3. Convert exports and imports one module edge at a time.

  4. Run the entry command after every edge.

Next, Mongoose Schemas and Models shows module boundaries meeting imported libraries.

Common errors, why they happen, and the exact repair

Symptom

Cause

Repair

Verification command

ReferenceError: require is not defined in ES module scope in .mjs

CommonJS syntax entered ESM

Use import, or rename intentional CommonJS to .cjs

node app.mjs or node app.cjs

ReferenceError: module is not defined in ES module scope

module.exports was used in ESM

Use export

node app.mjs

ERR_MODULE_NOT_FOUND after from './invoice'

Local ESM extension is missing

Use ./invoice.mjs

node esm/app.mjs

A .js CommonJS file breaks after "type": "module"

The package now treats .js as ESM

Convert its syntax or rename it .cjs

Run the package entry command

The exports shortcut has a trap. In wrong.cjs, exports = { answer: 42 }; only rebinds the local shortcut, so console.log(require('./wrong.cjs')); prints {}. Use module.exports = { answer: 42 }; and it prints { answer: 42 }. This follows Node's documented module.exports binding.

ESM does not provide __dirname automatically. Use this portable repair:

js
import { fileURLToPath } from 'node:url';
import { dirname } from 'node:path';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
console.log(__dirname);

The printed path depends on your machine.

How interviews and coding exercises test module understanding

Predict first. The CommonJS cache demo prints 1 1 true; the ESM live binding prints 1 then 2; both invoices print 1475 under different contracts.

Now repair this broken.mjs:

js
const { invoiceTotal } = require('./invoice.cjs');
console.log(invoiceTotal(1250, 0.18));

Solution A keeps .mjs: use import invoice from './invoice.cjs';, then call invoice.invoiceTotal(1250, 0.18). Solution B moves the consumer to .cjs and keeps require. Both print 1475.

In five minutes, migrate invoice.cjs and app.cjs to .mjs, preserve the named invoiceTotal, include .mjs in the relative import, then prove it with node esm/app.mjs.

CommonJS vs ESM: the short version and next step

  • Use the format already established in the project.

  • Make new modern packages explicit instead of relying on syntax detection.

  • Use .cjs and .mjs when both systems must coexist.

  • Test interoperability edges instead of assuming a syntax-only rename is enough.

Two contracts, the same 1250 subtotal, the same 18% tax, and the same 1475 output. Continue with the Node.js, Express.js & MongoDB Course for backend practice, or the MERN Stack Course - Full Stack Development for a wider full-stack path.