Sub topic 11
Tracing resolution with traceResolution and explainFiles
This chapter assumes you can read a tsconfig.json and run tsc from a terminal. It also assumes you know the module and moduleResolution options and how package.json exports works, which earlier chapters covered. It turns those ideas into a debugging routine. When an import fails, you can ask the compiler what it tried instead of guessing.
Why guessing fails
Resolution errors are hard to fix because the message names the symptom, not the cause. Cannot find module './greet' can mean any of these:
- The file does not exist.
- The extension is missing under
nodenext. - The importing file is treated as CommonJS when you expected ESM.
- An
exportsmap hides the file you want. - The package ships JavaScript but no declarations.
- The compiler uses a different
tsconfig.jsonthan you think.
Two compiler flags show the actual lookups:
| Flag | Question it answers |
|---|---|
| `--traceResolution` | What did the compiler try for each import, and what did it pick? |
| `--explainFiles` | Why is each file in the program, and in which module format is it treated? |
Both flags only print information. They never change how resolution works. Add --noEmit so that nothing is written to outDir while you investigate.
A failing project to practice on
Create a small project. This is the setup used in the rest of the chapter.
{
"name": "trace-demo",
"type": "module",
"version": "1.0.0"
}{
"compilerOptions": {
"module": "nodenext",
"target": "es2022",
"strict": true,
"outDir": "dist"
},
"include": ["src"]
}// src/greet.ts
export function greet(name: string): string {
return `Hello, ${name}`;
}// src/main.ts
import { greet } from "./greet";
console.log(greet("world"));Running npx tsc --noEmit reports error TS2835. The message says that relative import paths need explicit file extensions in ECMAScript imports under node16 or nodenext, and it suggests ./greet.js. This message already contains the answer. Real projects rarely fail so clearly, so the trace is worth reading even here.
Reading a traceResolution log
Run the trace and save it to a file, because the output is long:
npx tsc --noEmit --traceResolution > trace.log
grep -n "greet" trace.logOn Windows PowerShell, use Select-String greet trace.log instead of grep. The relevant block looks like this. The exact wording varies between TypeScript versions, so treat this as an abridged example.
======== Resolving module './greet' from '/project/src/main.ts'. ========
Module resolution kind is not specified, using 'NodeNext'.
Resolving in ESM mode with conditions 'import', 'types', 'node'.
Loading module as file / folder, candidate module location '/project/src/greet', target file types: TypeScript, Declaration.
File name '/project/src/greet' has a '' extension - stripping it.
Directory '/project/src/greet' does not exist, skipping all lookups in it.
======== Module name './greet' was not resolved. ========Every block begins and ends with a line of = characters, so you can skim to the one you want. Read it in four steps.
- The header line names the specifier exactly as written and the importing file. If the specifier or the file is not the one you expected, you are looking at the wrong import.
- The mode line says
Resolving in ESM modeorResolving in CJS mode, followed by the active conditions. This line shows how the compiler classified the importing file. A wrong format is the most common root cause undernodenext. - The candidate lines show each path tried and each extension substituted. In ESM mode the compiler does not append
.tsto an extensionless relative path, so the lookup stops. - The footer line reports success with the final path or reports that the module was not resolved.
Change the import to ./greet.js and trace again. The block now contains these lines:
File name '/project/src/greet.js' has a '.js' extension - stripping it.
File '/project/src/greet.ts' exists - use it as a name resolution result.
======== Module name './greet.js' was successfully resolved to '/project/src/greet.ts'. ========This is the behavior you studied before. The .js in the source names the emitted file, and the compiler maps it back to greet.ts to find the types.
Tracing a package import
Bare specifiers such as example-lib produce longer logs because the compiler walks up the directory tree looking for node_modules. Filter for the package name:
npx tsc --noEmit --traceResolution | grep -n "example-lib"Lines worth finding in a package trace:
Found 'package.json' at '.../node_modules/example-lib/package.json'confirms that the package was located at all.Matched 'exports' condition 'types'orMatched 'exports' condition 'import'shows which branch of theexportsmap was chosen.Resolving real pathshows where a symlinked package (npm workspaces,pnpm) points.'package.json' does not have a 'typesVersions' fieldrules out one redirect mechanism.Resolution for module 'x' was found in cache from location '...'means that this specifier was already resolved from the same directory. The detailed lookup appears earlier in the log, so search for the first occurrence.
The order of conditions matters. If default appears before types inside an exports branch, the compiler takes the .js file and then finds no declarations. The trace shows this as a match on default where you expected a match on types.
A trace for a package ends in one of three ways. You should recognize each:
- Resolved to a
.d.tsor.tsfile. Types work. - Resolved to a
.jsfile only. The import works at runtime, but you get TS7016, "Could not find a declaration file". Install@types/...or add declarations. - Not resolved. Check the
exportsmap, the importing file's mode, and whether the package is installed.
Finding out why a file is in the program
--explainFiles answers a different question. It prints every file in the program and the reason for its inclusion.
npx tsc --noEmit --explainFiles > explain.log
grep -n -A4 "src/main.ts" explain.logTypical output for the demo project:
src/greet.ts
Imported via "./greet.js" from file 'src/main.ts'
File is ECMAScript module because 'package.json' has field "type" with value "module"
src/main.ts
Matched by include pattern 'src' in 'tsconfig.json'
File is ECMAScript module because 'package.json' has field "type" with value "module"Each file has two kinds of lines:
- Inclusion reasons such as
Imported via,Matched by include pattern, orRoot file specified for compilation. A file you did not expect to compile is often pulled in by a broadincludepattern or by an import chain from another file. - Format reasons such as
File is ECMAScript module because ...orFile is CommonJS module because 'package.json' does not have field "type". These lines explain the classification that the mode line in--traceResolutionreported.
The format reasons name the deciding factor directly. The possible reasons are the file extension (.mts, .cts), the nearest package.json type field, or neither. This ends many arguments about why one file is treated as CommonJS.
The output also lists library files such as lib.es2022.d.ts and type packages from node_modules/@types. If you have a global type conflict, explainFiles shows which @types package was auto-included. The types compiler option limits that inclusion.
A diagnostic routine
The flowchart shows an order that wastes the least time.
Common error codes and where to look first:
| Code | Meaning | First place to look |
|---|---|---|
| TS2307 | Cannot find module or its declarations | Footer line, then candidate paths |
| TS2835 | Relative import needs an explicit extension | The specifier in the header line |
| TS2792 | Cannot find module; consider `nodenext` | `moduleResolution` in the effective config |
| TS7016 | Module found but has no declarations | Whether resolution ended at a `.js` file |
| TS1479 | CommonJS file imports an ES module with `require` | Mode line and `explainFiles` format reasons |
Check the configuration the compiler uses
Often the trace shows a mode you did not set. Print the configuration after all extends chains are applied:
npx tsc --showConfigIf the output lacks "module": "nodenext", the compiler read a different file. A common cause is running tsc in a folder that has a tsconfig.json with "files": [] and project references, while the real settings live in tsconfig.app.json. In that case pass the project explicitly:
npx tsc -p tsconfig.app.json --noEmit --traceResolutionThe first lines of the trace log name the resolution kind, as in Module resolution kind is not specified, using 'NodeNext'. That line comes from the same configuration, so it is a quick check.
Limits of the trace
The trace describes what TypeScript does. It does not describe what Node.js or your bundler does at runtime. A successful trace means that type checking will find the file. It does not prove that the emitted JavaScript runs.
- Under
nodenext, the trace follows Node rules closely, so a clean trace is a good sign. - Under
bundler, the compiler is deliberately permissive. For example, it accepts extensionless relative imports. A clean trace does not prove that the target runtime accepts those imports. Your bundler's own resolution is the final authority. pathsaliases appear in the trace as a rewrite attempt. The bundler or runtime must perform the same rewrite, or the program fails after compilation. The trace shows only the type-checking side.
For runtime questions, run the emitted code with Node, or run the bundler, and compare the result with the trace.
Common mistakes when tracing
- Reading the whole log. Search for the specifier instead. Logs for medium projects run to thousands of lines.
- Tracing with the wrong working directory. Relative
tsconfig.jsonlookup depends on where you runtsc. Check the first lines of the log for the importing path. - Forgetting that results are cached. If a specifier appears many times, only the first resolution has full detail. Search for the earliest match.
- Fixing the symptom. Adding
// @ts-ignorehides the error and keeps the broken resolution. Fix the specifier or the configuration instead.
Exercise
Under nodenext, your file src/app.ts imports "./util" and the compiler reports TS2835. You change it to "./util.ts" and now get a different error about importing with a .ts extension. Which specifier should you write, and which line in the traceResolution output confirms that it works?
Show answer
Write "./util.js". The extension names the emitted JavaScript file, and the compiler maps it back to util.ts. The confirming line is the footer, "Module name './util.js' was successfully resolved to '/.../src/util.ts'", preceded by "File '/.../src/util.ts' exists - use it as a name resolution result."
Exercise
A trace for a package import shows "Resolving in CJS mode with conditions 'require', 'types', 'node'" although you wrote the import in a file you believed was an ES module. Which flag shows why the file was classified that way, and what are the possible reasons?
Show answer
Run tsc with --explainFiles. Its format line for the importing file says why the file is CommonJS or ES module. The reasons are the file extension (.mts is ESM, .cts is CommonJS) or the "type" field of the nearest package.json ("module" gives ESM, otherwise CommonJS).