Sub topic 3
Importing CommonJS from ESM and the Reverse
Assume you can write TypeScript imports and exports, run tsc, and recognize basic Node.js CommonJS (CJS) and ES module (ESM) files. Under nodenext, TypeScript follows Node.js runtime rules. Under bundler, the bundler usually handles the final module conversion.
Importing CommonJS from ESM
An ESM file can import a CommonJS package. The default import is the most reliable form because CommonJS exports one value through module.exports.
// legacy.cjs
module.exports = { greet: (name: string) => `Hello, ${name}` };
// main.mts
import legacy from "./legacy.cjs";
console.log(legacy.greet("Ada"));TypeScript may allow named imports from CommonJS by analyzing its source, but Node.js cannot always provide those names at runtime. Prefer the default import when the package documentation does not guarantee named exports.
Importing ESM from CommonJS
CommonJS cannot use require() to load an ES module. Use dynamic import() instead:
// loader.cts
export async function loadMessage() {
const module = await import("./message.mjs");
return module.default;
}Dynamic import returns a promise, so the calling code must use await or .then().
`paths` aliases and their limits
A paths alias changes how TypeScript resolves an import during checking. It does not rewrite the import in emitted JavaScript.
{
"compilerOptions": {
"module": "nodenext",
"moduleResolution": "nodenext",
"paths": {
"@/*": ["src/*"]
}
}
}A runtime such as Node.js still needs a matching configuration, or the alias will fail after compilation. Bundlers often provide their own alias setting. Keep TypeScript and runtime or bundler aliases synchronized.
Diagnosing resolution
Ask TypeScript to show its lookup process:
npx tsc --noEmit --traceResolution
npx tsc --noEmit --explainFilestraceResolution shows candidate paths, package conditions, and failed lookups. explainFiles shows why files entered the compilation.
Choosing a mode
Choose nodenext when Node.js runs the emitted files directly or when publishing a Node-compatible library. Choose bundler when a bundler resolves extensions, aliases, and package conditions. Do not use bundler to hide imports that Node.js will execute unchanged.
Publishing for both modes
Publish separate ESM and CJS files. Use package.json conditional exports, and place types before default in each condition:
{
"exports": {
".": {
"import": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
},
"require": {
"types": "./dist/index.d.cts",
"default": "./dist/index.cjs"
}
}
}
}Exercise
Which mode should you choose when Node.js executes the emitted JavaScript directly?
Show answer
Choose nodenext, because it models Node.js module and extension rules.