The moduleResolution Compiler Option
What you'll learn: How to configure TypeScript's strategy for locating and resolving imported modules using the moduleResolution compiler option.
What Is Module Resolution?
When you write import { something } from "my-module" in TypeScript, the compiler needs to find that module's type definitions. Should it look in node_modules? Should it check for .ts files or .d.ts files? Should it follow Node.js rules or browser bundler rules? The moduleResolution option tells TypeScript which algorithm to use when answering these questions.
Think of it like choosing a GPS routing algorithm: the destination is the same, but the path you take (and the rules you follow) depends on whether you're driving, walking, or taking public transit.
The Five moduleResolution Strategies
1. node (Classic Node.js)
Mimics Node.js's CommonJS resolution for node_modules. Looks for index.js, package.json "main" field, etc. This was the standard for years.
2. classic (Legacy)
The original TypeScript strategy. Rarely used today. Walks up directory trees looking for .ts files. No node_modules awareness.
3. node16 (Node.js ESM)
Designed for Node.js 16+ with native ECMAScript modules. Requires explicit .js extensions in imports and respects package.json "exports" field.
4. nodenext (Future Node.js)
Identical to node16 but tracks the latest Node.js resolution behavior as it evolves.
5. bundler (Modern Tooling)
Assumes a bundler like Webpack, Vite, or esbuild handles resolution. Relaxes Node.js rules (no extension required) while keeping modern module features.
Choosing Your Strategy
- Building for Node.js with ESM? → Use
node16ornodenext - Using a bundler (Vite, Webpack)? → Use
bundler - Legacy Node.js/CommonJS project? → Use
node - Ancient TypeScript project? → You might see
classic, but migrate away
The moduleResolution setting must align with your runtime environment and module system (module option). Mismatches cause "cannot find module" errors even when files exist.
Key Takeaway: The moduleResolution option tells TypeScript how to find modules—choose the strategy that matches your runtime (Node.js ESM, bundler, etc.) to avoid resolution headaches.