Modules
ES modules vs CommonJS — import/export syntax, live bindings, static structure and tree shaking, dynamic import, top-level await, module resolution in Node and bundlers, package.json exports, and dual-package hazards.
A module is a file with its own scope that explicitly exports some values and imports others. Modules replaced the early web's global-variable soup. JavaScript has two module systems you'll meet: ES modules (ESM), the standard, and CommonJS (CJS), Node's original system.
ES modules
// math.js
export const PI = 3.14159;
export function area(r) { return PI * r * r; }
export default class Calculator { /* ... */ } // one default export per module
// app.js
import Calculator, { area, PI as pi } from "./math.js"; // default + named (+ rename)
import * as math from "./math.js"; // namespace object
import "./polyfills.js"; // run for side effects only
export { area } from "./math.js"; // re-export (barrel files)In browsers: <script type="module" src="app.js">. In Node: use .mjs, or "type": "module" in package.json.
Key properties of ESM
- Static structure:
import/exportmust be at the top level with string-literal specifiers. Tools can analyse the dependency graph without running code — enabling tree shaking (removing unused exports) and early errors for missing names. - Live bindings: an import is a read-only view of the exporter's variable, not a copy.
- Strict mode always; top-level
thisisundefined. - Evaluated once: every importer shares the same module instance (modules are natural singletons).
- Asynchronous loading: the graph is fetched and linked before any code runs, enabling top-level await.
// counter.js
export let count = 0;
export function increment() { count++; }
// main.js
import { count, increment } from "./counter.js";
increment();
console.log(count); // 1 — live binding sees the update
count = 5; // TypeError: imports are read-onlyLoading phases
- Construction: fetch and parse each module, find its imports, recursively build the module graph.
- Instantiation: allocate memory for every export and wire up imports to point at them (live bindings) — no code has run yet.
- Evaluation: run each module's top-level code, dependencies first (post-order).
Cycles are allowed: thanks to live bindings, a module in a cycle can see the other's exports once they're initialised (accessing them too early throws a TDZ ReferenceError).
Dynamic import and top-level await
// Load code on demand: returns a promise for the module namespace
button.addEventListener("click", async () => {
const { openEditor } = await import("./editor.js"); // separate chunk, loaded lazily
openEditor();
});
// Top-level await (ESM only)
const config = await fetch("/config.json").then((r) => r.json());
export const apiUrl = config.apiUrl;Bundlers turn import() into code splitting points: React's lazy() and Next.js's route-based splitting rely on it.
CommonJS
// math.cjs
const PI = 3.14159;
function area(r) { return PI * r * r; }
module.exports = { PI, area }; // or exports.area = area
// app.cjs
const { area } = require("./math.cjs");
const lodash = require("lodash");How it works: Node wraps each file in a function (function (exports, require, module, __filename, __dirname) { ... }), runs it synchronously on first require, and caches module.exports.
| ES modules | CommonJS | |
|---|---|---|
| Syntax | import / export | require() / module.exports |
| Loading | Asynchronous, graph linked before execution | Synchronous, on demand at the require call |
| Structure | Static (analysable, tree-shakeable) | Dynamic (require anywhere, computed paths) |
| Bindings | Live, read-only | A copy of module.exports values at the time of require |
| Top-level await | Yes | No |
__dirname, __filename | Use import.meta.dirname, import.meta.filename (Node 20.11+) | Available |
| Browser support | Native | Needs a bundler |
Interop in Node
- ESM can
importCJS:module.exportsbecomes the default export (and Node detects some named exports). - CJS loading ESM: historically only via
await import(); modern Node (22+) supportsrequire()of synchronous ESM graphs (no top-level await).
Module resolution
What does import x from "lodash" actually load?
- Relative/absolute specifiers (
./utils.js,/lib/a.js) are file paths. In Node ESM and browsers, extensions are required. - Bare specifiers (
lodash,@scope/pkg/sub) are looked up innode_modulesdirectories walking up from the importing file, then resolved using the package'spackage.json. - Browsers need import maps for bare specifiers (or a bundler/CDN).
- TypeScript's
moduleResolution(bundler,nodenext) mirrors these rules (TypeScript basics).
package.json fields
{
"name": "my-lib",
"type": "module",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.js",
"require": "./dist/index.cjs"
},
"./utils": "./dist/utils.js"
},
"sideEffects": false
}"type": how.jsfiles are interpreted (module= ESM,commonjs= CJS default)."exports": the package's public entry points, with conditional exports per environment (import,require,browser,node,types). Anything not listed can't be imported — an encapsulation boundary."sideEffects": false: tells bundlers unused files can be dropped safely.
Bundlers
Browsers can load native ESM, but production apps still usually bundle: fewer requests, minification, tree shaking, code splitting, transpiling TypeScript/JSX, and handling CSS and assets.
| Tool | Notes |
|---|---|
| Vite | Native ESM dev server (instant start), Rollup/Rolldown for production builds |
| esbuild | Extremely fast Go-based bundler/transpiler |
| Rollup | Library bundling; pioneered tree shaking |
| webpack | Mature, highly configurable |
| Turbopack / Rspack | Rust-based successors for large apps (Next.js uses Turbopack) |
Tree shaking only works well with ESM, side-effect-free modules, and named exports — import _ from "lodash" pulls in everything; import { debounce } from "lodash-es" doesn't.
- ES modules are the standard: static imports/exports, live read-only bindings, strict mode, evaluated once.
- Static structure enables tree shaking; import() enables lazy loading and code splitting.
- CommonJS loads synchronously and copies module.exports; still common in Node.
- Node decides ESM vs CJS by extension and package.json type; exports defines a package's entry points.
- Bundlers resolve, transform, tree-shake and split code for production.