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.

Intermediate 4 min readLesson 9 of 12

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

JavaScript
// 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/export must 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 this is undefined.
  • 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.
JavaScript
// 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-only

Loading phases

  1. Construction: fetch and parse each module, find its imports, recursively build the module graph.
  2. Instantiation: allocate memory for every export and wire up imports to point at them (live bindings) — no code has run yet.
  3. 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

JavaScript
// 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

JavaScript
// 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 modulesCommonJS
Syntaximport / exportrequire() / module.exports
LoadingAsynchronous, graph linked before executionSynchronous, on demand at the require call
StructureStatic (analysable, tree-shakeable)Dynamic (require anywhere, computed paths)
BindingsLive, read-onlyA copy of module.exports values at the time of require
Top-level awaitYesNo
__dirname, __filenameUse import.meta.dirname, import.meta.filename (Node 20.11+)Available
Browser supportNativeNeeds a bundler

Interop in Node

  • ESM can import CJS: module.exports becomes the default export (and Node detects some named exports).
  • CJS loading ESM: historically only via await import(); modern Node (22+) supports require() 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 in node_modules directories walking up from the importing file, then resolved using the package's package.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

JSON
{
  "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 .js files 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.

ToolNotes
ViteNative ESM dev server (instant start), Rollup/Rolldown for production builds
esbuildExtremely fast Go-based bundler/transpiler
RollupLibrary bundling; pioneered tree shaking
webpackMature, highly configurable
Turbopack / RspackRust-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.

Key takeaways
  • 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.