TypeScript Reference ยท tsconfig: Language, Modules and Emit Options
TypeScript rewriteRelativeImportExtensions option
Reference for rewriteRelativeImportExtensions: how relative .ts import paths become .js in the emitted code, which paths are rewritten, and when to use it.
rewriteRelativeImportExtensions tells the compiler to change the file extension in relative import paths while it emits JavaScript. You write import { add } from "./math.ts"; the output contains import { add } from "./math.js". It was added in TypeScript 5.7.
The goal is one source tree that works in two worlds: runtimes that execute .ts files directly (which need the .ts extension in imports) and the compiled .js output (which needs .js). Turning the option on also lets you write .ts extensions in imports without enabling noEmit, because the emitted code stays correct.
{ "compilerOptions": { "rewriteRelativeImportExtensions": true, "module": "nodenext", "outDir": "dist" } }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Syntax
{ "compilerOptions": { "rewriteRelativeImportExtensions": true } }
| Part | Description |
|---|---|
| Value | true or false. Default: false. |
| Mapping | .ts to .js, .mts to .mjs, .cts to .cjs, .tsx to .js (or .jsx with "jsx": "preserve"). |
| Scope | Relative specifiers only, in static import, export ... from, import x = require() and import() calls whose argument is a string literal. |
Edge cases: a computed import(name) cannot be rewritten because the compiler does not know the string. Declaration-file paths and non-relative paths are untouched. Imports that already end in .js stay as they are.
Usage notes
- Requires an emitting build. The point is the emitted
.js; withnoEmitthe option does nothing useful (use allowImportingTsExtensions instead). - Allows
.tsin imports by itself. You do not need to setallowImportingTsExtensionsas well. - Node workflow. Develop with
node file.ts(type stripping), publish withtsc. Both read the same source files. Combine it with erasableSyntaxOnly. - Paths mapped by
pathsare not rewritten. Aliases are not relative, so they follow your bundler or runtime rules (see paths). - Output files must exist. The rewritten
./math.jsonly works ifmath.tsis also compiled; keep every imported file inside the project. - Not a transpiler for bare packages. An import such as
"lodash/fp.ts"is left alone.