Sub topic 11
When the Compiler Cannot Find a Module
This chapter assumes you can run tsc and read a diagnostic's location and code. It also assumes you know ES module import syntax and have a project with a tsconfig.json. Module errors are different from type mismatches. The compiler is not comparing two types here. It failed to locate a file or package before it could check anything.
The error family
Three diagnostics cover most cases:
| Code | Message starts with | Meaning |
|---|---|---|
| TS2307 | Cannot find module 'x' or its corresponding type declarations | Resolution found nothing usable |
| TS2835 / TS2834 | Relative import paths need explicit file extensions in ECMAScript imports | A relative import in an ES module lacks `.js`, under `node16` or `nodenext` |
| TS7016 | Could not find a declaration file for module 'x' | The JavaScript was found, but no types came with it |
TS2307 is the general one. The other two are more specific and usually tell you the fix.
How resolution works
For each import specifier, the compiler runs an algorithm set by the moduleResolution option. The result of module and moduleResolution together decides which algorithm runs. With "module": "NodeNext", the compiler follows Node's rules.
- A relative specifier such as
./greetingis resolved against the importing file's folder. - A bare specifier such as
lodashis looked up innode_modules, walking up through parent folders. - For a package, the compiler reads
package.jsonfields (types,exports,main) to find a declaration file. If there is none, it checks for@types/<name>. - Only files that resolve to
.ts,.tsx,.d.ts, or (withallowJs) JavaScript count as found.
Case 1: a wrong path
The simplest cause is a misspelled file name. Suppose src/greeting.ts exists:
export function greet(name: string): string {
return `Hello, ${name}`;
}and src/index.ts misspells it:
import { greet } from "./greting";
console.log(greet("Ada"));$ npx tsc --noEmit --pretty false
src/index.ts(1,23): error TS2307: Cannot find module './greting' or its corresponding type declarations.The column, 23, points at the opening quote of the specifier. That tells you the problem is the string, not the imported name. Check case as well as spelling. A macOS or Windows machine will happily resolve ./Greeting to greeting.ts at runtime, while a Linux CI machine will not.
Case 2: the missing extension under NodeNext
If you correct the spelling and the project uses "module": "NodeNext" with "type": "module" in package.json, you may see a different error:
src/index.ts(1,23): error TS2835: Relative import paths need explicit file extensions in ECMAScript imports when '--moduleResolution' is 'node16' or 'nodenext'. Did you mean './greeting.js'?Node's ES module loader never guesses extensions, so TypeScript refuses to either. The fix looks odd but is correct:
import { greet } from "./greeting.js";
console.log(greet("Ada"));You write .js even though the source file is .ts. The import describes the file that will exist after compilation, and TypeScript maps .js back to greeting.ts when it type-checks. Do not write .ts here unless you have enabled allowImportingTsExtensions.
Whether a file counts as ESM or CommonJS depends on the nearest package.json "type" field, or on a .mts or .cts extension. The same extensionless import can be valid in one file and an error in another.
Case 3: a package that is not installed
import _ from "lodash";
console.log(_.chunk([1, 2, 3, 4], 2));src/index.ts(1,15): error TS2307: Cannot find module 'lodash' or its corresponding type declarations.If node_modules/lodash does not exist, run npm install lodash. A fresh clone without npm install produces this error for every dependency at once. That is a cascade, so fix it once rather than line by line.
Case 4: the package exists but has no types
After you install lodash, the error changes. Under strict (which includes noImplicitAny), you get TS7016:
src/index.ts(1,15): error TS7016: Could not find a declaration file for module 'lodash'. '/project/node_modules/lodash/lodash.js' implicitly has an 'any' type.
Try `npm i --save-dev @types/lodash` if it exists or add a new declaration (.d.ts) file containing `declare module 'lodash';`The message lists the fixes. In order of preference:
- Install community types:
npm install --save-dev @types/lodash. - Check whether a newer version of the package ships its own types.
- Write a declaration file yourself.
For option 3, create src/types/legacy-lib.d.ts:
declare module "legacy-lib" {
export function parse(input: string): number[];
}Two details make this work. The file must be matched by the include setting in tsconfig.json. It must also contain no top-level import or export. If it does, TypeScript treats the file as a module, and declare module then tries to augment an existing module instead of declaring a new one.
The shorthand declare module "legacy-lib"; makes every import from it any. That removes the error but also removes all checking. Use it only as a temporary step.
Case 5: files that are not code
Bundlers let you import CSS, images, or JSON. TypeScript only knows about these if you tell it. For JSON, set "resolveJsonModule": true. For other assets, declare a wildcard module:
declare module "*.css" {
const classes: Record<string, string>;
export default classes;
}This only satisfies the type checker. Your bundler still has to handle the file at build time.
Case 6: configuration
If the file exists and the path is right, look at tsconfig.json.
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"strict": true,
"noEmit": true,
"paths": {
"@app/*": ["./src/*"]
}
},
"include": ["src"]
}include: a.d.tsfile outsideincludeis invisible, so adeclare modulethere has no effect.paths: this maps an alias such as@app/greetingto a file for type checking only. TypeScript does not rewrite the alias in emitted JavaScript. Your runtime or bundler needs a matching alias setting.moduleResolution: an older value such asnode10ignores a package'sexportsfield. A package that works in a bundler project may fail to resolve underNodeNext, or the reverse. When a package's types seem to exist but are not found, check which value you are using.
Asking the compiler what it did
When the cause is not obvious, ask the compiler. These commands do not need any code changes:
npx tsc --noEmit --traceResolution
npx tsc --showConfig
npx tsc --noEmit --explainFiles--traceResolution prints each lookup, with lines like Resolving module './greting' from '/project/src/index.ts', followed by every path it tried. The output is long, so pipe it to a file or filter it with grep for the specifier you care about. --showConfig prints the final configuration after extends is applied, which catches a setting inherited from another file. --explainFiles lists every file in the program and why it was included.
Exercise
A project uses "module": "NodeNext" and "type": "module". The line import { greet } from "./greeting"; produces TS2835. What is the fix, and why must you write the extension as .js when the source file is greeting.ts?
Show answer
Change the import to import { greet } from "./greeting.js";. Node's ES module loader does not guess extensions, so the specifier must name the file that exists at runtime. The source is compiled to greeting.js, so the import uses that name. TypeScript maps ./greeting.js back to greeting.ts when it type-checks.
Exercise
You added declare module "legacy-lib" { export function parse(input: string): number[]; } in a .d.ts file, but TS7016 still appears. Name two things to check.
Show answer
First, check that the file is covered by the include setting in tsconfig.json, because the compiler ignores a declaration file it never loads. Second, check that the file has no top-level import or export. With one, the file is a module, and declare module becomes an augmentation instead of a new declaration.