Study notes · 8% of the exam

Modules, Packages and npm

Know how Node.js picks a module system for each file, how CommonJS and ES module resolution differ, how the two interoperate, and how package.json and semver decide what gets installed and what can be imported.

Key points

  1. 1

    .mjs is always ESM and .cjs always CommonJS; .js follows the nearest package.json "type", and Node 22.7+ detects ESM syntax in ambiguous files (with a warning when a typeless package.json exists).

  2. 2

    CommonJS resolves extensions, index.js and node_modules folders up the tree, caches by resolved path, and runs each file in a wrapper (exports, require, module, __filename, __dirname).

  3. 3

    The ESM resolver needs exact file extensions, rejects directory imports, needs with { type: 'json' } for JSON, and has no require or __dirname (use import.meta.dirname).

  4. 4

    Since Node 22.12 and 20.19, require() can load ES modules without top-level await and returns their namespace; an export named "module.exports" customises what it returns.

  5. 5

    Importing CommonJS from ESM: the default import is always module.exports; named imports come from static detection by cjs-module-lexer and only cover simple patterns.

  6. 6

    exports defines every reachable path, tries conditions in object order (put default last), and blocks everything else with ERR_PACKAGE_PATH_NOT_EXPORTED; imports gives private # aliases.

  7. 7

    Caret keeps the left-most non-zero part (^0.2.3 → <0.3.0), pre-releases only match their own tuple, and npm ci installs the lockfile exactly and fails on mismatches.

Common traps

  • Reassigning exports = {...} or replacing module.exports during a circular require leaves other modules holding a stale object.

  • Listing "default" first in a conditional exports object shadows every other condition.

  • Code that relies on packages hoisted by npm (phantom dependencies) breaks under pnpm or after an unrelated upgrade.

Test yourself on Modules, Packages and npm

Ten questions, with the answer and explanation after each one.