Sub topic 5
Extensions in relative imports
This chapter assumes you can read a tsconfig.json, know that module and moduleResolution are separate options, and know that a package's "type" field decides whether .js files are ESM or CommonJS. The previous chapter covered how nodenext resolves imports in general. This chapter covers one rule that trips up almost everyone who switches to it: relative imports need file extensions, and the extension is not the one on disk.
The rule in one example
Take a project with this layout and a package.json that contains "type": "module":
src/
greet.ts
main.tsWith "module": "nodenext", main.ts must import greet.ts like this:
// src/main.ts
import { greet } from "./greet.js";
console.log(greet("world"));// src/greet.ts
export function greet(name: string): string {
return `Hello, ${name}!`;
}The import says ./greet.js, but no greet.js exists in src/. TypeScript knows that a source file greet.ts will be emitted as greet.js, so it maps the specifier back to the source. The compiler does not rewrite your import specifiers. The string you write is the string Node.js sees at runtime, so it has to name the file that will exist after compilation.
Why the extension is required
Node.js resolves ES module imports literally. It does not try adding .js, and it does not look for index.js inside a directory. The CommonJS require() function does both of those things. Since nodenext mirrors Node.js, the compiler enforces the stricter ESM behavior in ESM files, so you find the mistake at compile time and not as a runtime ERR_MODULE_NOT_FOUND.
If you omit the extension in an ES module file, you get one of these errors:
error TS2835: Relative import paths need explicit file extensions in ECMAScript
imports when '--moduleResolution' is 'node16' or 'nodenext'. Did you mean './greet.js'?
error TS2834: Relative import paths need explicit file extensions in ECMAScript
imports when '--moduleResolution' is 'node16' or 'nodenext'. Consider adding an
extension to the import path.TS2835 appears when the compiler can find a likely target and suggests it. TS2834 appears when it cannot.
Which extension to write
Write the extension of the output file, not the source file.
| Source file | Emitted file | Write in the import |
|---|---|---|
| `greet.ts` | `greet.js` | `./greet.js` |
| `greet.tsx` | `greet.js` (or `greet.jsx` when `jsx` is `preserve`) | `./greet.js` or `./greet.jsx` |
| `greet.mts` | `greet.mjs` | `./greet.mjs` |
| `greet.cts` | `greet.cjs` | `./greet.cjs` |
| `greet.d.ts` (hand-written declarations for `greet.js`) | none | `./greet.js` |
The .mts and .cts extensions force a format regardless of package.json. A .mts file is always ESM and a .cts file is always CommonJS. A plain .ts file takes its format from the nearest package.json: ESM when that file has "type": "module", CommonJS otherwise. The extension rule depends on the format of the file that contains the import, not the file being imported.
Directory imports are also gone
In ESM files, a path that points at a directory does not resolve to its index file. If src/utils/index.ts exists, this fails:
import { slugify } from "./utils";You must name the file:
import { slugify } from "./utils/index.js";Barrel files (index.ts files that re-export other modules) are the usual place this shows up. Every export * from "./thing" inside one needs ./thing.js.
CommonJS files are different
The rule applies to imports that Node.js will treat as ESM. In a CommonJS file under nodenext, TypeScript compiles import statements to require() calls, and require() supports extensionless paths and directory index lookups. So in a package with no "type": "module", these all work:
// src/main.ts in a CommonJS package
import { greet } from "./greet";
import { slugify } from "./utils";This creates a trap during migration. When you add "type": "module" to package.json, every .ts file in the package switches to ESM and every extensionless relative import becomes an error at once. Plan to fix them in one pass. Tools such as a find-and-replace on from "./ help, but review the result, since directory imports need /index.js, not just .js.
Dynamic import() is a special case. It always uses ESM resolution, even inside a CommonJS file, so it needs the extension:
// In a CommonJS file
async function loadPlugin() {
const mod = await import("./plugin.js");
return mod;
}What the compiler does with a specifier
The decision for a relative import in nodenext follows the format of the importing file.
Importing `.ts` extensions directly
Writing ./greet.ts is an error by default:
error TS5097: An import path can only end with a '.ts' extension when
'allowImportingTsExtensions' is enabled.The reason is that the emitted JavaScript would keep ./greet.ts and Node.js could not find that file in dist/. Two options change this:
allowImportingTsExtensionspermits.tsspecifiers, but it only works when the compiler is not producing JavaScript (noEmitoremitDeclarationOnly). It suits projects where a bundler or a runtime that executes TypeScript handles the files.rewriteRelativeImportExtensions(TypeScript 5.7 and later) lets you write./greet.tsand hastscrewrite it to./greet.jsin the output. It only rewrites relative paths, and it leaves bare package specifiers andpathsaliases alone.
A configuration that writes .ts in source and still emits runnable JavaScript looks like this:
{
"compilerOptions": {
"module": "nodenext",
"target": "es2022",
"strict": true,
"outDir": "dist",
"rewriteRelativeImportExtensions": true
}
}With this option, import { greet } from "./greet.ts" in src/main.ts becomes import { greet } from "./greet.js" in dist/main.js. Without it, stay with .js in source.
How bundler mode changes this
Under "moduleResolution": "bundler", the extension requirement is dropped. Bundlers resolve extensionless paths and directory indexes themselves, so TypeScript accepts all of these:
import { greet } from "./greet";
import { greet as g2 } from "./greet.js";
import { slugify } from "./utils";The .js form still maps back to greet.ts, so a codebase can move between modes without rewriting every import. The .ts form needs allowImportingTsExtensions, and the bundler config usually has noEmit set already, so that option is cheap to enable.
Common mistakes
- Writing
./greet.tsin source. You get TS5097 unless you enable one of the options above. - Writing
./greetin an ESM file. You get TS2835 or TS2834. - Importing a directory in an ESM file. Use
./dir/index.js. - Fixing the error by adding
.jsand then finding the runtime still fails. In that caseoutDirorrootDirprobably places the file somewhere your layout did not expect. Check thatdist/greet.jsexists and that the relative position of the two files is the same indist/as insrc/. - Mixing
.mtsand.tsfiles and forgetting to use.mjsin the specifier for the.mtsfile.
Quick check
The build with "module": "nodenext" and "type": "module" reports TS2835 for import { x } from "./lib/helpers" where src/lib/helpers.ts exists. The fix is to write ./lib/helpers.js. If helpers were instead a directory containing index.ts, the fix would be ./lib/helpers/index.js.
Exercise
A package has "type": "module" and "module": "nodenext" in its tsconfig. The file src/api/index.ts exports a function, and src/main.ts contains import { handler } from "./api";. The compiler reports an error. What do you write instead, and why does the specifier name a file that does not exist in src/?
Show answer
Write import { handler } from "./api/index.js";. In an ES module file, Node.js does not add extensions or look for a directory's index file, so the specifier must name the exact emitted file. TypeScript maps ./api/index.js back to the source file src/api/index.ts, and the specifier stays unchanged in the compiled output, where dist/api/index.js does exist.
Exercise
A file named src/legacy.cts imports ./format (extensionless) from src/format.cts, and also contains const m = await import("./report") inside an async function, where report is src/report.mts. Which import will TypeScript reject under nodenext, and what should each specifier be?
Show answer
The static extensionless import of ./format is fine, because a .cts file is CommonJS and require-style resolution allows extensionless paths. The dynamic import("./report") is rejected, because dynamic import always uses ESM resolution and requires an extension. Write import("./report.mjs"), since the target is a .mts file that emits report.mjs. You could also write ./format.cjs for the first import, which is optional here.