Sub topic 1
TypeScript Module Resolution: nodenext and bundler
Prerequisites
You should be comfortable with TypeScript import and export statements, basic tsconfig.json settings, and the difference between Node.js CommonJS and ES modules.
What module resolution does
Module resolution is the process TypeScript uses to turn an import specifier into a file. For example, when it sees ./greet.js, it determines which source file provides that module and where its type declarations are.
Resolution is separate from module format. The module option describes the JavaScript module format TypeScript emits. The moduleResolution option describes the rules used to find imported files.
ESM and CommonJS: how a file's format is decided
ESM, or ECMAScript Modules, is JavaScript's standard module system. CommonJS is Node.js's older module system, commonly using require and module.exports.
Under nodenext, TypeScript decides a file's format from its extension and the nearest package.json:
| File or setting | Format |
|---|---|
| `.mts` or `.mjs` | ESM |
| `.cts` or `.cjs` | CommonJS |
| `.ts` in a package with `"type": "module"` | ESM |
A .ts file in a package without "type": "module" is treated as CommonJS. The emitted file normally receives the corresponding .js, .mjs, or .cjs extension.
The `module` and `moduleResolution` options
For code executed directly by Node.js, use nodenext:
{
"compilerOptions": {
"module": "nodenext",
"target": "es2022",
"strict": true,
"outDir": "dist"
}
}Setting module to nodenext also selects compatible Node.js resolution rules. For bundler-based applications, module: "preserve" with moduleResolution: "bundler" keeps the import style for the bundler to process.
How `nodenext` resolves imports
In an ESM file, relative imports must include the runtime extension. The extension names the emitted file, so a TypeScript source file can still use .js:
import { greet } from "./greet.js";
console.log(greet("world"));nodenext also reads package fields such as exports, selecting entries according to whether the importing code uses ESM or CommonJS.
Exercise
Which option determines how TypeScript finds an imported file: module or moduleResolution?
Show answer
moduleResolution determines the lookup rules; module determines the module format TypeScript emits.