Sub topic 2
How TypeScript Resolves Your Package
Assume you know TypeScript imports, tsconfig.json, npm, and basic ESM and CommonJS syntax. Module resolution is the process TypeScript uses to find the JavaScript file and declaration file for an import.
Choosing a resolution mode
TypeScript provides three relevant strategies:
| Mode | Models | Best for |
|---|---|---|
| `node10` | Older Node.js behavior | Legacy packages |
| `node16` or `nodenext` | Modern Node.js ESM and CommonJS rules | Node.js libraries |
| `bundler` | Modern bundler behavior | Packages built with Vite, esbuild, or similar tools |
node10 mainly checks fields such as main and types. It does not fully understand conditional exports.
node16 and nodenext inspect the importing file and package settings. They distinguish ESM from CommonJS and honor the exports map. Use nodenext when your package targets Node.js and should follow Node's current rules.
bundler understands package exports but does not require explicit file extensions in relative imports. It fits applications whose bundler performs the final resolution.
{
"compilerOptions": {
"module": "NodeNext",
"moduleResolution": "NodeNext",
"declaration": true,
"strict": true
}
}Older entry points
Before exports, packages commonly used these fields:
mainpoints to the CommonJS or default JavaScript entry point.moduleoften points bundlers to an ESM entry point.typespoints TypeScript to a.d.tsdeclaration file.
These fields remain useful as fallbacks, but different tools may interpret them differently.
The `exports` field
Use exports as the authoritative public API. Put the types condition before default:
{
"exports": {
".": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
},
"./locale": {
"types": "./dist/locale/index.d.ts",
"default": "./dist/locale/index.js"
}
}
}The second entry is a subpath export. It allows @acme/slugify/locale. Files not listed in exports cannot be imported by package consumers.
Dual ESM and CommonJS packages
If both module systems are required, give each condition matching JavaScript and declaration files:
{
"exports": {
".": {
"import": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
},
"require": {
"types": "./dist/index.d.cts",
"default": "./dist/index.cjs"
}
}
}
}The ESM declaration uses .d.ts; the CommonJS declaration uses .d.cts. Test both import styles before publishing.
Exercise
Which resolution mode best matches a Node.js package that supports ESM and CommonJS?
Show answer
nodenext, because it follows Node.js module rules and understands conditional exports.