Sub topic 1
What module resolution does
Every import in your code names a module with a string. The compiler needs to turn that string into a file so it can read the types. That step is module resolution. This chapter builds the working model you need for the rest of the tutorial and shows the errors you will see when the model breaks.
Prerequisites
This chapter assumes you can:
- Write TypeScript with
importandexportstatements. - Read a basic
tsconfig.jsonand runtscfrom the command line. - Recognize that Node.js runs both CommonJS (
require) and ES modules (import). - Read a
package.jsonwith fields such asmainanddependencies.
You do not need to know the exports field or the details of nodenext yet. Later chapters cover them.
The problem resolution solves
Consider this import:
import { greet } from "./greet.js";The string "./greet.js" is a module specifier. TypeScript must decide which file on disk it refers to. It needs that file to learn the type of greet. If it cannot find a file, the import is an error. If it finds the wrong file, your types describe code that is not what runs.
Specifiers come in two kinds:
| Kind | Example | Meaning |
|---|---|---|
| Relative | `./greet.js`, `../util/index.js` | A path from the importing file |
| Bare (non-relative) | `express`, `@scope/pkg`, `lodash/fp` | A package name, optionally with a subpath |
Relative specifiers are resolved against the directory of the importing file. Bare specifiers are resolved by searching installed packages. A third kind, path aliases such as @app/utils, looks like a bare specifier but is configured by you. A later chapter covers aliases.
Resolution finds types, and it does not change your code
Two facts explain most confusing behavior.
First, TypeScript uses resolution only to build its program and check types. It does not rewrite specifiers when it emits JavaScript. If you write "./greet.js", the emitted file contains "./greet.js" unchanged.
Second, TypeScript does not run your code. At runtime, Node.js or a bundler performs its own resolution on the emitted specifier. Resolution in tsc is a prediction of what the runtime will do. When the prediction and the runtime disagree, you get code that type-checks but crashes with ERR_MODULE_NOT_FOUND, or the reverse.
That is why moduleResolution has several modes. Each mode copies the rules of one runtime.
What the compiler looks for
For a relative import, the compiler appends candidate extensions to the path and checks each in turn. In the classic Node-style lookup, an import of ./greet tries roughly this order:
./greet.ts./greet.tsx./greet.d.ts- A directory
./greet/with apackage.jsonthat names a types entry ./greet/index.ts,./greet/index.tsx,./greet/index.d.ts
Under nodenext, an ES module file must write the extension itself, and the rules for directories change. The next chapters cover those details.
For a bare import such as express, the compiler walks up the directory tree. It checks node_modules/express in the importing file's folder, then in the parent folder, and so on up to the filesystem root. Inside the package it looks for type information. A package can ship its own declarations, for example through a types field or an exports map. If it does not, the compiler checks for a separate node_modules/@types/express package.
The result of a successful lookup is always a TypeScript source file (.ts, .tsx, .mts, .cts) or a declaration file (.d.ts, .d.mts, .d.cts). Resolution can also land on a plain .js file when allowJs is on. Otherwise a lone .js file gives the compiler nothing to read.
module and moduleResolution are different settings
Two options in compilerOptions are easy to confuse:
| Option | Question it answers | Affects |
|---|---|---|
| `module` | What module syntax should the emitted JavaScript use? | Output: `import`/`export` or `require`/`exports` |
| `moduleResolution` | How should specifiers be mapped to files? | Input: which file an import points to |
You can think of module as controlling the output format and moduleResolution as controlling how the compiler searches. For most projects the two should agree with your runtime, so TypeScript links them. Setting module to nodenext also selects nodenext resolution:
{
"compilerOptions": {
"module": "nodenext",
"target": "es2022",
"strict": true,
"outDir": "dist"
}
}For code that a bundler processes, you tell TypeScript to leave the module syntax alone and use bundler-style lookup. TypeScript only checks types, and the bundler produces the files you run:
{
"compilerOptions": {
"module": "preserve",
"moduleResolution": "bundler",
"target": "es2022",
"strict": true,
"noEmit": true
}
}The available values for moduleResolution are node10 (the old default, formerly spelled node), node16, nodenext, bundler, and classic. This tutorial focuses on nodenext and bundler. Avoid classic, which predates Node-style lookup, and treat node10 as legacy because it ignores package.json exports.
A small example
Start with a project that uses nodenext. Its package.json contains "type": "module", which makes .js and .ts files ES modules.
// src/greet.ts
export function greet(name: string): string {
return `Hello, ${name}!`;
}// src/main.ts in a package whose package.json has "type": "module"
import { greet } from "./greet.js";
console.log(greet("world"));The file on disk is greet.ts, yet the import says greet.js. This is deliberate. TypeScript does not rewrite the specifier, so the emitted dist/main.js still imports ./greet.js. After compilation dist/greet.js exists, and Node.js finds it. The compiler accepts the .js spelling and maps it back to greet.ts when it looks for types. If you wrote ./greet instead, nodenext would reject it, because Node.js would not find a file with that exact name at runtime.
Common errors and what they mean
The error code tells you which stage of resolution failed.
| Error | Message (shortened) | Usual cause |
|---|---|---|
| TS2307 | Cannot find module 'x' or its corresponding type declarations | No file or package matched the specifier |
| TS2792 | Cannot find module 'x'. Did you mean to set `moduleResolution` to `nodenext`... | The mode in use cannot see a package that only has an `exports` map |
| TS2835 | Relative import paths need explicit file extensions in ECMAScript imports | A relative import in an ES module file under `nodenext` has no extension |
| TS7016 | Could not find a declaration file for module 'x' | The package was found but has no types, and `noImplicitAny` is on |
TS7016 differs from the others. The runtime package exists, so resolution succeeded, but no .d.ts was found for it. The usual fix is to install @types/x or to write a short declaration yourself.
Seeing what the compiler did
You do not have to guess why an import failed. The --traceResolution flag prints each lookup the compiler attempts, and --explainFiles shows why each file is in the program:
npx tsc --noEmit --traceResolution | grep "greet"
npx tsc --noEmit --explainFilesThe first command filters the long trace down to lines that mention greet. You will see each candidate path tried and which one was accepted. The second command lists every file in the program with the import or setting that pulled it in. A later chapter works through these outputs in detail. For now, remember that the tools exist and that a trace is the quickest way to learn which rule applied.
Working model to carry forward
- A specifier is either relative or bare. Each kind has its own search.
- Resolution only decides which file supplies types. It does not edit your imports.
- The runtime resolves the emitted specifier again, so
moduleResolutionshould predict that runtime. modulecontrols emitted syntax, andmoduleResolutioncontrols lookup. Somemodulevalues select a matching resolution mode.- Error codes (TS2307, TS2792, TS2835, TS7016) point to different failure stages.
Exercise
In a project with "module": "nodenext" and "type": "module", you write import { greet } from "./greet"; and the compiler reports TS2835. The file on disk is src/greet.ts. What do you change in the import, and why does the new specifier name a .js file that does not exist in src?
Show answer
Change the import to import { greet } from "./greet.js";. In an ES module file under nodenext, relative imports need an explicit extension because Node.js requires one at runtime. TypeScript does not rewrite specifiers on emit, so the specifier must name the file that will exist after compilation, which is dist/greet.js. The compiler maps greet.js back to greet.ts to find the types.
Exercise
What is the difference between the module and moduleResolution options, and which of the two decides which file an import points to?
Show answer
module sets the module syntax of the emitted JavaScript (import/export or require/exports). moduleResolution sets the algorithm that maps a specifier to a file, so it decides which file an import points to. Setting module to nodenext also selects nodenext resolution.