Sub topic 6
How TypeScript resolves an import to a file
This chapter assumes you can write import and export statements, run tsc, and edit a tsconfig.json. It also assumes you know what package.json and node_modules are. It covers how the compiler turns the string in an import statement into a file on disk, and why the answer depends on your settings.
What resolution does
An import such as import { add } from "./math.js" contains only a string, called the module specifier. The compiler must map that string to a source file or a declaration file. From that file it reads the types of the imported names.
Resolution is separate from emit. TypeScript does not rewrite specifiers when it produces JavaScript. The specifier you write is the specifier the runtime sees. Most resolution bugs come from writing something the type checker accepts but the runtime rejects, or the reverse.
When resolution fails, you get an error like this:
error TS2307: Cannot find module './math' or its corresponding type declarations.The moduleResolution strategies
The moduleResolution option selects the algorithm. Each strategy imitates a different runtime or tool.
| Strategy | Models | Reads `exports` | Extensionless relative imports | Directory `index` imports |
|---|---|---|---|---|
| `node10` | Old Node.js CommonJS lookup | No | Yes | Yes |
| `node16` / `nodenext` | Current Node.js, both ESM and CJS | Yes | CJS files only | CJS files only |
| `bundler` | Webpack, Vite, esbuild and similar tools | Yes | Yes | Yes |
| `classic` | Pre-Node TypeScript behavior | No | Yes | No |
If you set module to node16 or nodenext, moduleResolution defaults to the matching value. If you set module to esnext or preserve, you should set moduleResolution to bundler yourself. Avoid classic. It exists for historical reasons and does not look in node_modules the way Node.js does.
{
"compilerOptions": {
"target": "es2022",
"module": "nodenext",
"strict": true,
"outDir": "dist"
},
"include": ["src"]
}With this configuration the compiler behaves like Node.js. Choose the strategy that matches whatever runs your code. A mismatch type-checks cleanly and then fails at run time.
Relative imports
A specifier that starts with ./, ../, or / is relative. The compiler builds a path from the importing file's directory and probes for a match.
For import "./math.js" under nodenext, the compiler maps the written extension to its TypeScript counterpart and tries these files in order:
./math.ts./math.tsx./math.d.ts
The mapping works the same way for .mjs (to .mts and .d.mts) and .cjs (to .cts and .d.cts). This is why you write .js in a TypeScript source file. The runtime will load the compiled math.js, and the compiler finds the .ts file that produces it.
Under node10 and bundler, an extensionless specifier like ./math is accepted. The compiler tries math.ts, math.tsx, and math.d.ts. If none exists and ./math is a directory, it reads ./math/package.json for a types or main entry, then tries ./math/index.ts, ./math/index.tsx, and ./math/index.d.ts.
ESM and CJS files in Node.js
Under node16 and nodenext, the same strategy behaves differently depending on the importing file. Node.js decides whether a file is ESM or CJS:
- A
.mtsfile is ESM, and a.ctsfile is CJS. - A
.tsor.jsfile takes its format from the"type"field of the nearestpackage.json."type": "module"means ESM. Otherwise it is CJS.
Inside an ESM file, Node.js requires full extensions and does not resolve directory indexes. The compiler enforces the same rules:
// src/main.ts, in a package with "type": "module"
import { add } from "./math.js"; // OK
import { sub } from "./math"; // error TS2835: did you mean "./math.js"?
import { helper } from "./utils"; // error: directory imports are not supported in ESM
import { sub as sub2 } from "./utils/index.js"; // OKInside a CJS file, require-style lookup applies, so extensionless specifiers work. Because the rules depend on the file, one project can legitimately contain both behaviors.
Bare specifiers and node_modules
A specifier without a leading dot, such as "lodash" or "@scope/pkg/sub", is a bare specifier. The compiler looks for a matching package in node_modules. It starts in the importing file's directory and walks up through each parent directory until it finds the package or reaches the root.
Within a package folder, the lookup differs by strategy.
Under node10, the compiler ignores exports. It checks, in order:
- The
typesfield (ortypings) inpackage.json. - The
mainfield, replacing the extension with.d.tsor.ts. index.d.tsat the package root.
Under node16, nodenext, and bundler, the compiler reads the exports field first. If exports exists, it is authoritative. Files and subpaths not listed there cannot be imported, even if they exist on disk. If exports is absent, the compiler falls back to types and main as above.
Export conditions
An exports entry can have conditions, which are keys such as types, import, require, and default. The compiler matches conditions in the order they appear in the object and picks the first one that applies. The conditions that apply are:
types, always.importfor an import from an ESM file, orrequirefor an import from a CJS file (node16andnodenext).importfor every import underbundler.nodeunder the Node.js strategies.default, always.
{
"name": "my-lib",
"type": "module",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.js",
"require": "./dist/index.cjs"
}
}
}Falling back to @types
If the package itself has no declaration file, the compiler also looks in node_modules/@types. For "express" it checks node_modules/@types/express. For a scoped package such as @scope/pkg, the folder name joins the scope and name with two underscores: node_modules/@types/scope__pkg.
If neither location has types but a JavaScript file exists, the import compiles under non-strict settings and the module is typed any. Under noImplicitAny (included in strict) you get:
error TS7016: Could not find a declaration file for module 'legacy-lib'.You can fix that with an @types package or an ambient declaration, both covered in other chapters.
The whole lookup at a glance
Debugging resolution
When an import fails or resolves to an unexpected file, ask the compiler to show its work. The --traceResolution flag prints every path it tries and the result:
npx tsc --noEmit --traceResolution | grep "my-lib"The output includes lines such as Resolving module 'my-lib' from '/app/src/main.ts', then each probe, then Module name 'my-lib' was successfully resolved to '/app/node_modules/my-lib/dist/index.d.ts'. Two other flags are useful:
--explainFileslists every file in the program and the reason it was included.--showConfigprints the configuration after defaults andextendsare applied. This shows you whichmoduleResolutionis really in use.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| TS2307 on a relative import under `nodenext` | Missing `.js` extension in an ESM file | Write `./file.js` |
| TS2307 on a package that exists | `exports` does not list the subpath, or `types` is missing from its conditions | Check the package's `exports`, or use the exact subpath it exposes |
| TS7016 for a package | No bundled types and no `@types` package | Install `@types/pkg` or add a `declare module` |
| Types resolve in your editor but the program fails to start | Strategy is `bundler` or `node10`, but the runtime is Node.js ESM | Switch to `module: nodenext` |
| Wrong types for the CJS and ESM builds of a package | `types` condition missing or listed after `import` or `require` | Reorder conditions, or provide separate `.d.cts` files |
Summary of rules to remember
- The specifier is never rewritten, so write what the runtime needs.
- Relative imports probe
.ts,.tsx, and.d.tsby mapping the written extension. - Bare imports walk up
node_modules, readexportswhen the strategy supports it, and fall back to@types. - Under
nodenext, the importing file's format (ESM or CJS) changes the rules. --traceResolutionshows exactly what was tried.
Exercise
A project has "module": "nodenext" and "type": "module" in its package.json. The file src/app.ts contains import { run } from "./tasks";, and src/tasks.ts exists. The compiler reports an error. What is the error about, how do you fix it, and what command shows how the compiler searched?
Show answer
In an ESM file under nodenext, relative imports need an explicit extension, so the compiler reports TS2835 (cannot resolve ./tasks; did you mean ./tasks.js?). Change the import to "./tasks.js". The compiler maps .js to tasks.ts, and Node.js loads the compiled tasks.js. Run npx tsc --noEmit --traceResolution to see every path the compiler tried.