Sub topic 2
Extensions in Relative Imports
Assume you know basic TypeScript imports, exports, and tsconfig.json. This chapter focuses on how TypeScript finds files and types under nodenext and bundler.
Extensions in `nodenext`
Module resolution is the process of turning an import such as "./greet.js" into a source file and its type declarations.
In an ES module file under nodenext, a relative import must include an extension. Write the extension of the emitted JavaScript file, not the TypeScript source file:
// src/main.ts
import { greet } from "./greet.js";
console.log(greet("world"));TypeScript checks src/greet.ts, then emits JavaScript that imports ./greet.js. The import remains valid after compilation.
Whether a file is ESM or CommonJS depends on its extension and nearby package.json. For example, .mts is always ESM, .cts is always CommonJS, and .ts follows the package's "type" field.
How TypeScript Finds Types
TypeScript resolves a module's runtime entry and its type declaration separately. It looks for declarations such as index.d.ts, a "types" or "typings" field, or a matching types condition in an exports map.
For a local greet.ts, TypeScript gets types directly from that file. For an installed package, it follows the package metadata and then loads the selected .d.ts file.
Reading `exports` Conditions
An exports map controls which paths consumers may import. Conditions select entries for different callers:
{
"exports": {
".": {
"import": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
},
"require": {
"types": "./dist/index.d.cts",
"default": "./dist/index.cjs"
}
}
}
}For an ESM import, TypeScript selects the import branch. It uses the types entry for checking and the default entry to describe the runtime file. Condition order matters, so place "types" before "default".
How `bundler` Differs
Bundlers often resolve extensionless imports and TypeScript source extensions before producing final JavaScript. With "moduleResolution": "bundler", this is valid:
import { greet } from "./greet";Use bundler when a bundler owns runtime resolution. Use nodenext when Node.js runs the emitted files directly.
Exercise
Why does an ESM import commonly use "./greet.js" when the source file is greet.ts?
Show answer
The import must name the emitted JavaScript file that Node.js loads after TypeScript compilation.