Node.js Modules
Modules define boundaries. In Node, the choice between CommonJS and ES modules affects syntax, tooling, and interop.
CommonJS
CommonJS (require / module.exports) was Node's original module system and loads modules synchronously from disk. Notice the node: prefix on built-in modules (such as node:path), which makes it unmistakable that an import comes from Node core rather than an npm package:
const path = require("node:path");
function buildConfigPath(dir) {
return path.join(dir, "config.json");
}
module.exports = { buildConfigPath };
ES modules
ECMAScript Modules (ESM) use static import and export syntax, matching browser JavaScript and enabling tree-shaking in bundlers. Enable ESM in Node by setting "type": "module" in package.json or naming files with the .mjs extension, and always include explicit file extensions on relative imports:
import path from "node:path";
export function joinPath(base, file) {
return path.join(base, file);
}
Design rules
Clean module boundaries prevent circular dependencies and keep refactors safe:
- Minimal public surface: Export only the functions and types other modules actually need; keep helpers file-private.
- One system per project: Standardize on ESM for new Node projects (or CommonJS if maintaining an older stack) rather than mixing both unnecessarily.
- Avoid circular imports: If module A imports module B and B imports A, extract the shared types or helpers into a third module C.
Practice
Practice structuring a multi-file Node package:
- Create
math.mjsexporting two pure functions and import them fromindex.mjs. - Import
node:pathandnode:fs/promisesusing thenode:protocol prefix. - Verify what error Node throws if you omit the
.mjsextension in an ESM relative import.