Ch. 6 · Node.js

Node.js ESM and CommonJS Boundaries

Node.js ESM and CommonJS Boundaries. Learn the reasoning, a practical example, common mistakes and an interview exercise.

~2 min readbeginnerupdated Oct 3, 2026

Module interpretation follows extension, package configuration and resolution rules. ESM and CommonJS have different exports and execution behavior.

Before you start

You should know JavaScript promises, asynchronous errors and the distinction between a process and a request. When following a server example, identify the resource owner and the point where work completes. Try experiments locally with bounded input instead of assuming production traffic behaves like a single request.

The practical goal is to reason through this situation: A package with type module treats its ordinary .js files as ES modules. Read the walkthrough first, then try the interview exercise before opening its answer. The important part is explaining the decision and its consequences, rather than remembering a definition alone.

Step-by-step walkthrough

Step 1: Inspect file interpretation

Check extension and the nearest package.json type field before changing import syntax.

Step 2: Read the package boundary

Inspect documented exports and distinguish ESM exports from CommonJS module.exports.

Step 3: Reproduce on supported Node

Use a minimal import with the project’s runtime and module settings, avoiding bundler-only assumptions.

Worked scenario

A package with type module treats its ordinary .js files as ES modules.

In a package marked type:module, ordinary .js files are ESM, while .cjs provides an explicit CommonJS file boundary. A dependency’s documented exports determine available public entry points. Changing default import to named import blindly may exchange one error for another without addressing the actual format or resolution rule.

Common mistake

Assuming every default import maps to a named CommonJS export creates interoperability bugs.

Verify the behavior

Run the minimal import outside the bundler, then within the application. Compare errors and inspect actual supported exports.

Interview exercise

Diagnose an import failure.

Answer and reasoning

Inspect package exports, module format and supported runtime before changing the import syntax.

Continue learning

Compare the scenario with the Node.js interview questions and test your understanding with the Node.js MCQs. For terminology and implementation details, consult the reference material.

More in Node.js

read ✓Node.js · hard

Node.js Clustering Across CPU Cores

Use cluster to run several workers on all cores, restart crashed workers, and understand shared-port and shared-state limits.

~2 min readread →
read ✓Node.js · hard

Node.js Password Hashing with scrypt

Store passwords as salted hashes with a slow key-derivation function, and compare candidates in constant time.

~2 min readread →
esc