Sub topic 4
How nodenext resolves imports
This chapter assumes you can write TypeScript imports and exports, edit tsconfig.json, and run tsc. It also assumes you know that Node.js runs both CommonJS (CJS) and ES modules (ESM), and that you have seen main and dependencies in package.json. Earlier chapters covered the module and moduleResolution options. Here you will see what the compiler does with one import under nodenext.
The compiler imitates Node.js, file by file
With "module": "nodenext", TypeScript sets moduleResolution to nodenext too. It then resolves each import the way Node.js would at runtime. The key difference from older settings is that the answer depends on the importing file. Two files in the same project can resolve the same specifier to different results, because Node.js treats them differently.
Resolution has three steps:
- Decide whether the importing file is ESM or CJS.
- Pick a resolution mode (
importorrequire) from that format and the syntax used. - Look up the specifier using the rules for that mode.
Step 1: the format of the importing file
TypeScript decides a file's format using the same rules as Node.js:
| File | Format under nodenext |
|---|---|
| `.mts`, `.mjs` | ESM |
| `.cts`, `.cjs` | CommonJS |
| `.ts`, `.tsx`, `.js`, `.jsx`, nearest `package.json` has `"type": "module"` | ESM |
| `.ts`, `.tsx`, `.js`, `.jsx`, nearest `package.json` has no `type` or `"type": "commonjs"` | CommonJS |
| `.ts` and similar files with no `package.json` above them | CommonJS |
"Nearest" means the first package.json found by walking up from the file's folder. In a monorepo, each package can therefore choose its own format.
The source syntax does not decide the format. You can write import and export in a CJS file. TypeScript compiles those statements to require and exports assignments. You can also write import() in either format.
Step 2: the resolution mode
The resolution mode controls which exports conditions TypeScript matches, and whether extensionless paths are allowed.
| Syntax | In an ESM file | In a CJS file |
|---|---|---|
| `import x from "m"` | `import` mode | `require` mode, because the statement compiles to `require` |
| `import("m")` | `import` mode | `import` mode |
| `import x = require("m")` | not allowed | `require` mode |
The dynamic import() row is the one people miss. A CJS file can reach ESM-only packages through import(), and TypeScript resolves it with the import condition.
Step 3a: relative imports
A relative specifier starts with ./ or ../. The rules depend on the mode.
In an ESM file, the specifier must be a full path with an extension. Node.js does no guessing in ESM, so TypeScript does not either. There is also no folder-to-index shortcut. The extension you write is the extension of the emitted JavaScript, not of your source file:
// src/main.ts in a package whose package.json has "type": "module"
import { greet } from "./greet.js"; // finds src/greet.ts
import { parse } from "./util/parse.js"; // finds src/util/parse.ts
import { cfg } from "./config.json" with { type: "json" };
console.log(greet("world"), parse("1"), cfg);For ./greet.js, TypeScript looks for greet.ts, then greet.tsx, then greet.d.ts. It maps .mjs to .mts and .cjs to .cts in the same way. Writing ./greet.ts is an error unless you enable allowImportingTsExtensions together with noEmit or emitDeclarationOnly. Recent compilers also offer rewriteRelativeImportExtensions for rewriting .ts specifiers on emit. This chapter keeps to the default .js convention.
In a CJS file, Node.js still applies its classic CJS lookup, so these all work:
// src/legacy.cts
import { greet } from "./greet"; // tries greet.ts, greet.tsx, greet.d.ts
import { parse } from "./util"; // tries util.ts, then util/index.ts
export const out: string = greet(parse("1"));The next chapter covers extension rules in more detail. For now, remember that the extension requirement follows the importing file's format.
Step 3b: bare specifiers and node_modules
A bare specifier has no leading dot, such as "example-lib" or "example-lib/utils". TypeScript walks up from the importing file and checks each node_modules folder, as Node.js does. In a matching package folder it follows this order:
- If
package.jsonhas anexportsfield, use it and ignoremain,module, andtypes. Match the subpath (.for the bare name) and choose a target using conditions. - If there is no
exports, use thetypesortypingsfield, thenmain, thenindexfiles. These fallbacks apply mainly in CJS-style lookups. - If nothing yields a TypeScript-readable file, look in
node_modules/@types.
Condition matching goes top to bottom through the keys in the object. The first key that matches wins. TypeScript matches these conditions:
types, which is used only by the compiler.importinimportmode, orrequireinrequiremode.node, because the target environment is Node.js.default, which always matches.
Order matters, so types must come before default inside each branch. Otherwise default matches first and TypeScript reads a .js file with no types.
Here is a package that ships separate ESM and CJS builds:
{
"name": "example-lib",
"type": "module",
"exports": {
".": {
"import": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
},
"require": {
"types": "./dist/index.d.cts",
"default": "./dist/index.cjs"
}
}
}
}Two consumers in the same project resolve the same specifier differently:
// app/src/main.mts (ESM, import mode)
import { make } from "example-lib";
// resolves to node_modules/example-lib/dist/index.d.ts
// app/src/old.cts (CJS, require mode)
import { make } from "example-lib";
// resolves to node_modules/example-lib/dist/index.d.cts
export const a = make();If the package declares an exports map, deep imports such as example-lib/dist/internal.js fail unless a pattern in the map exposes them. This matches Node.js, which blocks the same import at runtime. It also means a working deep import under an older node setting can break when you move to nodenext.
Two related features are worth knowing:
- Self-reference. A package can import itself by its own
namewhen it has anexportsfield. - Subpath imports. Specifiers starting with
#are looked up in theimportsfield of the nearestpackage.json, with the same condition rules. They are a Node.js-native alias system that does not need a bundler.
What the compiler emits
nodenext does not rewrite your specifiers. It checks them and emits what you wrote. If main.ts contains import { greet } from "./greet.js", the compiled dist/main.js contains the same line, and Node.js can run it. This is why the .js convention exists. The source specifier must already be correct for the output.
The settings that go with this behavior:
{
"compilerOptions": {
"module": "nodenext",
"target": "es2022",
"strict": true,
"outDir": "dist"
}
}Common errors and what they mean
| Error | Cause | Fix |
|---|---|---|
| TS2834 or TS2835: relative import paths need explicit file extensions | Extensionless or directory import in an ESM file | Write `./x.js` or `./dir/index.js` |
| TS2307: cannot find module | Specifier not matched, deep import blocked by `exports`, or no types found | Check the `exports` map and `node_modules/@types` |
| TS1479: CJS file importing an ES module | `require`-mode import of an ESM-only package on older compilers | Use `await import()`, or switch the file to ESM |
| TS1259 or TS2497 with `esModuleInterop` | Default-import shape mismatch with a CJS module | Check interop settings and the module's `export =` |
| TS1376 or TS1484 style type-only complaints | Importing a type without `import type` under `verbatimModuleSyntax` | Use `import type { T }` |
Putting it together
When you meet an unexpected resolution result under nodenext, ask these questions in order:
- What is the format of the importing file? Check the extension, then the nearest
package.json. - Which mode does the syntax produce?
- Is the specifier relative? If so, does it have the extension the format requires?
- Is it a package? Then read its
exportsmap top to bottom with that mode's conditions.
The final chapters of this tutorial show how to trace the compiler's actual lookups when these questions do not give the answer.
Exercise
A project has "type": "module" in its root package.json. The file src/tools.cts contains import { run } from "./runner"; and src/runner.ts exists. Does the import compile, and which resolution mode applies?
Show answer
It compiles. The .cts extension makes the file CommonJS, regardless of the package type. An import statement in a CJS file compiles to require, so the mode is require. CJS lookup allows extensionless relative paths, so ./runner resolves to runner.ts without an error.
Exercise
In an ESM file, import { make } from "example-lib" resolves to a plain .js file with no types, although the package ships .d.ts files. The package's exports has "import": { "default": "./dist/index.js", "types": "./dist/index.d.ts" }. What is wrong, and how do you fix it?
Show answer
Conditions match in key order, and default always matches, so it is chosen before types is reached. Move "types" above "default" inside the import branch. The same applies to the require branch.