FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Modern ESM & Tree-Shaking

ECMAScript module resolution, TypeScript bundler mode, and tree-shaking dead code elimination.

Freshness: current•14 min read•Software and Web Engineering

Key Learning Outcomes

  • ✓Configure TypeScript for modern bundlers
  • ✓Optimize static export graphs for tree-shaking
Full Technical Reference Document

Mental model

ECMAScript Modules (ESM) evaluate a static module dependency graph before executing user code, whereas legacy CommonJS (CJS) loads files imperatively at runtime whenever require() executes. Because ESM import and export declarations are statically analyzable without running JavaScript, modern bundlers (Vite, Rollup, esbuild, Turbopack, webpack 5) build an exact export-level reachability graph to eliminate unused code (Tree-Shaking). In TypeScript 5.x, choosing the right module + moduleResolution matrix (NodeNext for raw Node.js runtime vs. Bundler for Next.js/Vite apps) prevents subtle extensionless-import crashes, barrel-file bundle bloat, and dual-package singleton bugs.

Static Import Declaration
Build Static Dependency Graph
Resolve package.json exports Conditions
Tree-Shaking Dead Code Elimination
Emit Bundled Output Asset
Conceptual teaching model synthesized from:typescript-54-spec,tc39-ecma262

Theory

TypeScript separates runtime emit (module) from lookup strategy (moduleResolution), respecting Node's package.json "exports" conditional entrypoints ("types", "import", "require", "default") only when modern resolution modes are enabled.

TypeScript Setting PairExtensionless Relative Imports (./foo)?Enforces .js Extension on Relative ESM?Ideal Target
"module": "ESNext", "moduleResolution": "Bundler"AllowedNo (noEmit: true + Vite / Next.js / esbuild handles extensions)Frontend SPAs, Next.js App Router, monorepo apps compiled by bundlers
"module": "NodeNext", "moduleResolution": "NodeNext"Rejected when emitting ESMYes (import "./foo.js" maps cleanly to ./foo.ts at compile time)Node.js libraries, CLI tools, MCP servers executed directly by Node
Legacy "moduleResolution": "node" (node10)AllowedNo (ignores package.json "exports" map!)Deprecated; breaks modern scoped exports & dual CJS/ESM packages

"exports" Precedence, "sideEffects": false, and Barrel File Costs

When publishing internal TypeScript workspace packages consumed by both a Next.js app (Bundler) and a Node.js backend (NodeNext), always place "types" first inside every "exports" condition block (".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" }) because Node and TypeScript match keys in insertion order. Meanwhile, to make tree-shaking genuinely effective, set "sideEffects": false in library package.json manifests (excluding CSS imports like "*.css"!) and avoid deep "barrel files" (export * from ...) across massive utility directories: even with tree-shaking enabled, re-exporting 200 modules through one index.ts barrel can defeat unused-module pruning during dev builds and dramatically slow HMR and Vite/Vitest test startup.

json
// Shared workspace library package.json (consumed by Bundler and NodeNext targets cleanly)
{
"name": "@acme/telemetry-sdk",
"version": "1.2.0",
"type": "module",
"sideEffects": ["./src/register-globals.ts"],
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.js"
},
"./metrics": {
"types": "./dist/metrics.d.ts",
"import": "./dist/metrics.js"
}
}
}
json
// App tsconfig.json vs Node server tsconfig.json
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "Bundler",
"verbatimModuleSyntax": true,
"noEmit": true
}
}

Enabling "verbatimModuleSyntax": true guarantees import type { Foo } is erased cleanly rather than accidentally leaving runtime value imports behind that force unwanted module initialization side effects.

Alternatives and trade-offs

  • Native ESM ("type": "module" + NodeNext / Bundler): Full top-level await, crisp tree-shaking, browser/edge worker parity, strict "exports" encapsulation; requires .js extensions on compiled Node ESM relative imports (or Bundler / tsx / Node 22+ --experimental-strip-types).
  • Dual-Format Libraries (tsup / unbuild emitting .mjs + .cjs): Supports legacy Jest/CommonJS consumers alongside ESM Vite apps; risks the Dual-Package Hazard if stateful singletons (React Context, DB pools, Zod registries) load twice—once via import and once via require.
  • Single-Format Pure ESM Packages: Eliminates dual-package state bugs cleanly; requires older CommonJS scripts on Node < 20.19 / < 22 to load dynamically via await import(...) (Node 22.12+ supports require(esm) synchronously for non-TLA graphs).

Failure modes and misconceptions

  1. Dual-Package Singleton Split (instanceof Fails Across CJS & ESM): If an external plugin loads @acme/sdk via require() (dist/index.cjs) while your app loads it via import (dist/index.mjs), two independent module closures execute in Node memory—breaking React createContext, telemetry registries, and err instanceof SdkError. Publish pure ESM where possible or store cross-format state behind Symbol.for(...) on globalThis.
  2. Legacy "moduleResolution": "node" Failing on Modern Libraries: Modern packages shipping only "exports" (without a top-level "main" field matching nested paths) throw TS2307: Cannot find module under legacy node10 resolution. Upgrade all tsconfigs to Bundler or NodeNext.
  3. Top-Level Side Effects Blocking Tree-Shaking: Writing export const client = initHeavySdk() at module top level forces bundlers to preserve the module even if a caller only imports export type Config without "sideEffects": false and import type. Wrap initialization in lazy factory functions and annotate side-effect-free packages explicitly.
  4. Assuming barrel.ts Files Are Free After Build: Even when production Rollup/esbuild drops unused barrel exports, Jest, Vitest, tsx, and Next.js dev mode often parse all modules referenced by index.ts barrels before running a single unit test—turning 5 ms test suites into multi-second startups. Import directly from feature files or sub-path "exports".
Reflect before revealing the guide

Decision scenario

Your monorepo contains a Next.js 16 frontend (apps/web), an MCP Node.js service (packages/mcp-server), and a shared Zod contracts package (packages/contracts). Configure packages/contracts as pure "type": "module" with "sideEffects": false, ordered exports ("types" first), and "module": "NodeNext" + "moduleResolution": "NodeNext" ("verbatimModuleSyntax": true) using .js extensions on relative imports so both Node ESM and Next.js work seamlessly without emitting duplicate .cjs bundles; meanwhile configure apps/web with "module": "ESNext" + "moduleResolution": "Bundler" and replace giant catch-all barrels with subpath exports (@repo/contracts/bkt, @repo/contracts/auth) to slash client bundle size and dev compile time.

Learning outcomes

  • Contrast static ESM reachability graphs against imperative CJS require() execution and explain tree-shaking mechanics.
  • Choose cleanly between TypeScript "moduleResolution": "Bundler" and "NodeNext" across web apps and Node.js runtimes.
  • Prevent CJS/ESM dual-package singleton bugs and "exports" resolution failures using "types" ordering and pure ESM.
  • Protect tree-shaking and dev test speeds using "sideEffects": false, "verbatimModuleSyntax": true, and direct subpath imports.

Trade-offs

Modern ESM + "moduleResolution": "Bundler"/"NodeNext" delivers strong static dead-code elimination and unambiguous package.json encapsulation, while demanding stricter .js extension awareness in Node targets and vigilance against CJS dual-package singletons in mixed ecosystems.

Prerequisites & Related Concepts (2)

Private notes

0 words
Recommended Free Track
Free · Verifiable Credential

FS-201Production LLM Engineer

Design an observable full-stack LLM product from capability validation through interfaces retrieval evaluation security and operations.

37 concepts~35h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next