Sub topic 7
Interop between CommonJS and ES modules
Assume you know basic TypeScript types, can use import and export, and have run tsc with a tsconfig.json. This chapter focuses on the boundary between two JavaScript module formats: CommonJS and ES modules.
Two module formats
CommonJS is the older Node.js module system. It uses require to import values and module.exports to export them:
// legacy.cjs
function greet(name) {
return `Hello, ${name}`;
}
module.exports = greet;ES modules, also called ESM, use import and export:
// app.mts
import greet from "./legacy.cjs";
console.log(greet("Ada"));Node.js treats the value assigned to module.exports as the CommonJS module's default export when an ES module imports it. This makes the default import the most reliable form for CommonJS modules.
| Direction | Usually reliable form | Main risk |
|---|---|---|
| ESM imports CommonJS | Default import | Named imports may not be detected |
| CommonJS loads ESM | Dynamic `import()` | Loading is asynchronous |
| ESM imports ESM | Named and default imports | File and package settings must agree |
ESM importing CommonJS
When an ES module imports CommonJS, Node.js provides the CommonJS export as the default value. It may also detect named exports by examining the CommonJS source, but this detection is static and imperfect.
// settings.cjs
module.exports = {
port: 8080,
environment: "production"
};// server.mts
import settings from "./settings.cjs";
console.log(settings.port);
console.log(settings.environment);The default import works because settings is the object assigned to module.exports. Avoid relying on this form:
import { port } from "./settings.cjs";It might work in one version of Node.js and fail after the CommonJS code changes. Use a default import and access properties on the resulting object when consuming untyped or legacy CommonJS code.
TypeScript needs declarations to know the shape of a CommonJS module. A declaration can describe a CommonJS module that exports one function:
// legacy.d.cts
declare function greet(name: string): string;
export = greet;With esModuleInterop enabled, TypeScript allows the matching default import:
// app.ts
import greet from "./legacy.cjs";
console.log(greet("Ada"));CommonJS loading ESM
A CommonJS file cannot normally use synchronous require() to load an ES module. ESM loading is asynchronous, so use dynamic import():
// loader.cjs
async function main() {
const module = await import("./math.mjs");
console.log(module.add(2, 3));
}
main().catch(console.error);The result of import() is a module namespace object. Named exports are properties of that object, and the default export is available through module.default.
Compiler settings and runtime behavior
For a Node.js project that preserves modern module behavior, use the Node-aware module setting:
{
"compilerOptions": {
"target": "es2022",
"module": "nodenext",
"moduleResolution": "nodenext",
"strict": true,
"esModuleInterop": true,
"outDir": "dist"
},
"include": ["src"]
}module: "nodenext" makes TypeScript follow Node.js rules. The file extension and the nearest package.json determine whether a file is treated as CommonJS or ESM. Files ending in .mts are ESM, and files ending in .cts are CommonJS. A package with "type": "module" also treats ordinary .js files as ESM.
esModuleInterop mainly affects CommonJS output. It adds compatibility helpers so that a CommonJS require can support default-import syntax more naturally. It does not change how Node.js executes an ESM file, and it cannot make a synchronous require() load an asynchronous ES module.
The safest design is to keep one module format within an application when possible. At a boundary, document whether consumers should use a default import, named imports, or dynamic import(). Test the emitted JavaScript with the same Node.js version and package settings used in production.
Exercise
A CommonJS module assigns a function to module.exports. What import form is the most portable for an ES module consumer, and how should a CommonJS consumer load an ES module?
Show answer
Use a default import for the CommonJS value. A CommonJS consumer should use asynchronous dynamic import() to load the ES module.