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.
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 Pair | Extensionless Relative Imports (./foo)? | Enforces .js Extension on Relative ESM? | Ideal Target |
|---|---|---|---|
"module": "ESNext", "moduleResolution": "Bundler" | Allowed | No (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 ESM | Yes (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) | Allowed | No (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-levelawait, crisp tree-shaking, browser/edge worker parity, strict"exports"encapsulation; requires.jsextensions on compiled Node ESM relative imports (orBundler/tsx/ Node22+ --experimental-strip-types). - Dual-Format Libraries (
tsup/unbuildemitting.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 viaimportand once viarequire. - Single-Format Pure ESM Packages: Eliminates dual-package state bugs cleanly; requires older CommonJS scripts on Node
< 20.19/< 22to load dynamically viaawait import(...)(Node22.12+supportsrequire(esm)synchronously for non-TLA graphs).
Failure modes and misconceptions
- Dual-Package Singleton Split (
instanceofFails Across CJS & ESM): If an external plugin loads@acme/sdkviarequire()(dist/index.cjs) while your app loads it viaimport(dist/index.mjs), two independent module closures execute in Node memory—breaking ReactcreateContext, telemetry registries, anderr instanceof SdkError. Publish pure ESM where possible or store cross-format state behindSymbol.for(...)onglobalThis. - Legacy
"moduleResolution": "node"Failing on Modern Libraries: Modern packages shipping only"exports"(without a top-level"main"field matching nested paths) throwTS2307: Cannot find moduleunder legacynode10resolution. Upgrade all tsconfigs toBundlerorNodeNext. - 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 importsexport type Configwithout"sideEffects": falseandimport type. Wrap initialization in lazy factory functions and annotate side-effect-free packages explicitly. - Assuming
barrel.tsFiles 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 byindex.tsbarrels before running a single unit test—turning5 mstest suites into multi-second startups. Import directly from feature files or sub-path"exports".
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.