Sub topic 4
Module formats and module resolution
Assume you know basic TypeScript imports, exports, and functions. You should also be able to run npm and tsc from a terminal. This chapter focuses on how TypeScript chooses a module format and finds imported files.
Two decisions that work together
A module format describes how imports and exports are represented in JavaScript. Common formats include:
CommonJS, used byrequireandmodule.exports.ESNextorES2022, which preserveimportandexport.NodeNext, which follows Node.js rules for both CommonJS and ECMAScript modules.
Module resolution is the process TypeScript uses to locate the file named by an import. It checks relative paths, package metadata, file extensions, and package export rules.
These settings must match the runtime or build tool. Code that type-checks can still fail when Node.js or a bundler interprets the emitted imports differently.
| Environment | Typical `module` | Typical `moduleResolution` |
|---|---|---|
| Modern Node.js with package-aware modules | `NodeNext` | `NodeNext` |
| Bundler such as Vite or esbuild | `ESNext` | `bundler` |
| Older Node.js CommonJS application | `CommonJS` | `Node` |
Using NodeNext with native ESM
For a modern Node.js project, let Node.js determine whether a file is CommonJS or ESM. The "type": "module" field makes .js output use ECMAScript modules.
package.json:
{
"type": "module",
"scripts": {
"build": "tsc",
"start": "node dist/main.js"
}
}tsconfig.json:
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"rootDir": "src",
"outDir": "dist",
"strict": true,
"skipLibCheck": true
},
"include": ["src"]
}In an ESM TypeScript file, write the extension that the emitted JavaScript will have:
src/main.ts:
import { greet } from "./greet.js";
console.log(greet("Ada"));src/greet.ts:
export function greet(name: string): string {
return `Hello, ${name}`;
}Build and run the project with:
npm run build
npm startThe import uses .js even though the source file is greet.ts. After compilation, dist/greet.js exists, so the import remains valid at runtime.
Bundler resolution
Bundlers often resolve extensionless imports and package conditions themselves. For such projects, this configuration is common:
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "bundler",
"noEmit": true,
"strict": true,
"skipLibCheck": true
},
"include": ["src"]
}Here, TypeScript checks the source but does not emit JavaScript. The bundler performs the build. Do not use bundler resolution when Node.js will execute the emitted files directly unless your build process also rewrites imports appropriately.
How an import is resolved
Exercise
Why does a NodeNext TypeScript file commonly import "./greet.js" when the source file is greet.ts?
Show answer
The compiler emits greet.ts as greet.js. The .js specifier therefore matches the file that Node.js loads after compilation.