Sub topic 9
Importing CommonJS from ESM and the reverse
This chapter assumes you know how nodenext decides whether a file is ESM or CommonJS. That decision comes from the .mts, .cts, .mjs and .cjs extensions, or from the nearest package.json "type" field. It also assumes you have read the earlier chapters on nodenext resolution and extension rules. Here you will see what TypeScript allows when files of the two formats import each other, and how that matches what Node.js does at runtime.
Why interop needs its own rules
Under module: nodenext, TypeScript does not rewrite your imports to match one module system. It checks each file against the format that file will have at runtime. An import statement in an ESM file stays an import. In a CommonJS file the same statement is compiled to a require() call. Two consequences follow:
- The same-looking statement can be legal in one file and an error in the next.
- TypeScript can only model what Node does. Where Node's behaviour depends on the shape of the emitted JavaScript, the types may say yes while runtime says no.
The following table summarizes the four directions.
| Importer | Target | Static `import` | Dynamic `import()` |
|---|---|---|---|
| ESM | ESM | Works | Works |
| ESM | CommonJS | Works, with a different default binding | Works |
| CommonJS | CommonJS | Works, compiled to `require()` | Works |
| CommonJS | ESM | Error TS1479 on older settings | Works, and is the portable choice |
ESM importing CommonJS
An ES module can import a CommonJS module. Node loads the CommonJS file, takes its module.exports value, and uses that value as the default export. TypeScript models the same behaviour.
Suppose src/legacy.cts is a CommonJS file that TypeScript compiles to legacy.cjs:
// src/legacy.cts
export function add(a: number, b: number): number {
return a + b;
}
export default function shout(text: string): string {
return text.toUpperCase() + "!";
}The emitted CommonJS code sets exports.add and exports.default. Now import it from an ESM file, src/main.mts:
// src/main.mts
import legacy, { add } from "./legacy.cjs";
console.log(add(1, 2));
console.log(legacy.default("hello"));The default import legacy is the whole module.exports object, not the function marked export default. The function is one level down, at legacy.default. The following diagram shows the lookup.
Named imports and the lexer
The statement import { add } from "./legacy.cjs" works, but only because of how Node finds names. Node scans the CommonJS source with a tool called cjs-module-lexer and picks out recognizable patterns such as exports.add = .... TypeScript's emitted code uses those patterns.
TypeScript cannot run that lexer. If a CommonJS package builds its exports dynamically, the type declarations may promise a named export that Node never finds. The failure appears at runtime, not at compile time:
SyntaxError: Named export 'add' not found. The requested module './legacy.cjs'
is a CommonJS module, which may not support all module.exports as named exports.When you hit this, import the default and read the property from it:
// src/main.mts
import legacy from "./legacy.cjs";
const { add } = legacy;
console.log(add(2, 3));This form depends only on module.exports being an object, so it works however the exports were built.
Declarations that use `export =`
Older packages often ship declarations that use export =. This models a CommonJS module whose module.exports is a single function or object. From an ESM file under nodenext, the default import is that value:
// types/slugify.d.cts (describes a CommonJS package)
declare function slugify(input: string): string;
export = slugify;// src/main.mts
import slugify from "slugify";
console.log(slugify("Hello World"));Under nodenext, esModuleInterop is on by default. In an ESM file you do not write import * as slugify and then call it, because a namespace import of a CommonJS module gives you an object, not the function.
CommonJS importing ESM
The reverse direction is stricter, because require() is synchronous and ES modules may load asynchronously (an ES module can use top-level await). A CommonJS file therefore cannot always use a static import of an ES module.
Take a small ES module:
// src/greet.mts
export function greet(name: string): string {
return `Hello, ${name}`;
}A CommonJS file that imports it statically triggers an error under settings such as module: node18:
// src/report.cts
import { greet } from "./greet.mjs";
// error TS1479: The current file is a CommonJS module whose imports will
// produce 'require' calls; however, the referenced file is an ECMAScript
// module and cannot be imported with 'require'. Consider writing a dynamic
// 'import("./greet.mjs")' call instead.The fix is a dynamic import(). TypeScript leaves import() as written in CommonJS output under nodenext, so Node performs a real ESM load:
// src/report.cts
export async function render(name: string): Promise<string> {
const { greet } = await import("./greet.mjs");
return greet(name);
}The function is async because import() returns a promise. This is the main cost of the portable approach: every caller of render must now handle a promise too.
Features that exist in only one format
Some syntax belongs to a single format, and copying code between files can trigger errors:
import.meta.urland top-levelawaitwork in ESM files only.__dirname,__filenameandrequireare available in CommonJS files only.import fs = require("node:fs")andexport =are CommonJS-only forms. TypeScript rejects them in ESM files under nodenext.
When an ESM file needs to load a CommonJS value by path, use createRequire. This example assumes @types/node is installed:
// src/main.mts
import { createRequire } from "node:module";
const require = createRequire(import.meta.url);
const config: { port: number } = require("./config.cjs");
console.log(config.port);The require function is typed as returning any, so you must write the type yourself, as the annotation on config does here. Prefer a normal import when it works, because it gives you checked types.
Dual packages and the "same file twice" problem
A package that ships both index.js (ESM) and index.cjs (CommonJS) can be loaded twice in one process. One part of your program may import it and another may require it, and each gets a separate copy. Module-level state, such as a cache or a class used with instanceof, is then duplicated. TypeScript cannot detect this. It sees two declaration files, index.d.ts and index.d.cts, that happen to describe the same API. The exports map from the earlier chapter selects between them, and the next chapters on choosing a mode and publishing come back to this problem.
Checking your understanding of the failure modes
A short checklist helps when an import across formats fails:
- Identify the format of the importing file and of the target file. Use the extension first, then the nearest
package.json"type". - If a CommonJS file imports an ES module and you see TS1479, switch to
await import(...), or check your TypeScript and Node versions. - If an ESM file imports a CommonJS module and the default value looks wrong, remember that the default binding is
module.exports. Look for.defaulton it. - If a named import compiles but fails at runtime with "Named export not found", import the default and destructure.
Exercise
A file src/tool.cts contains export default function run() {}. Another file, src/main.mts, contains import tool from "./tool.cjs"; tool();. It compiles under nodenext, but the call fails at runtime. Why does it fail, and how do you fix it?
Show answer
tool.cts is CommonJS, so its default export is stored as exports.default. In the ESM file, the default import binds to the whole module.exports object, which is not callable. TypeScript reports this as an error too, because it models that binding. The fix is to call tool.default(), or to change tool.cts to use export = function run() {}, so that module.exports is the function itself and the default import is callable.
Exercise
A CommonJS file under module: nodenext must call a function from ./greet.mjs, and the code must also run on Node 20. Which import form should it use, and what changes for the code that calls it?
Show answer
Use a dynamic import("./greet.mjs"). Node 20 cannot require() an ES module by default, and a static import produces TS1479 under older settings. The caller must handle a promise, so the enclosing function becomes async or returns a promise.