Sub topic 7
Interop between CommonJS and ES modules
This chapter assumes you know the import and export forms, the difference between CommonJS (require, module.exports) and ES modules, and how to edit tsconfig.json. It covers what happens when the two formats meet, and how TypeScript's settings model that.
Why interop is a problem
CommonJS (CJS) loads files synchronously through require(). ES modules (ESM) have static import and export statements and load asynchronously. Node.js can run both, but the two formats do not map one to one:
- A CJS module has one export value,
module.exports. It can be a function, a class, or an object. - An ESM module has a set of named exports and one optional
defaultexport.
Every interop rule exists to bridge that difference. TypeScript has to model the bridge accurately, or it reports types that do not match what happens at runtime.
Which format is a file?
Under "module": "nodenext", TypeScript decides the format of each file separately, as Node does:
.mtsand.mjsfiles are ESM..ctsand.cjsfiles are CJS.- A
.tsor.jsfile takes its format from the nearestpackage.json."type": "module"makes it ESM. Otherwise it is CJS.
The format determines how an import statement is emitted. In an ESM file, import stays an import. In a CJS file, TypeScript rewrites it to require().
The four crossings
| From | To | Works? | How |
|---|---|---|---|
| ESM | CJS | Yes | `import` gives you `module.exports` as the default export |
| CJS | CJS | Yes | `require()`, or `import` compiled to `require()` |
| CJS | ESM | Depends | `await import()` always works. `require()` works in recent Node.js versions, but not in older ones |
| ESM | ESM | Yes | `import` |
Importing CJS from ESM
When an ESM file imports a CJS file, Node.js sets the default export to the whole module.exports value. Node.js also tries to detect named exports by scanning the CJS source for patterns such as exports.name = .... That scan is static and incomplete, so named imports from CJS can fail at runtime even when TypeScript accepts them.
Given this CJS file:
// lib.cjs
module.exports = {
add(a, b) {
return a + b;
},
};Importing it from an ESM file looks like this:
// main.mts
import lib from "./lib.cjs";
console.log(lib.add(1, 2));The default import is the reliable form. A named import such as import { add } from "./lib.cjs" may work or throw, depending on whether Node.js detected the name. Using the default import and reading properties from it avoids that dependency.
Loading ESM from CJS
A CJS file cannot use a static import for an ESM-only module in older Node.js versions, because require() of an ES module threw ERR_REQUIRE_ESM. The portable fix is dynamic import(), which returns a promise:
// legacy.cts
async function main(): Promise<void> {
const { add } = await import("./math.mjs");
console.log(add(1, 2));
}
main();Newer Node.js releases can require() a synchronous ES module, and recent TypeScript versions allow that under nodenext. If you support older Node.js versions, use import().
If a CJS file statically imports an ESM file under an older TypeScript setup, you may see error TS1479: the current file is a CommonJS module whose imports will produce require calls, but the referenced file is an ECMAScript module. The error means exactly what it says. Switch to import() or convert the file to ESM.
`export =` and `import = require()`
TypeScript has syntax for a CJS module that assigns a single value to module.exports:
// greet.d.ts
declare function greet(name: string): string;
export = greet;A file that uses export = cannot also have other exports. The matching import form is:
import greet = require("./greet");That form is accurate but old-fashioned. With esModuleInterop enabled, you can use the standard default import instead:
// consumer.ts (with esModuleInterop enabled)
import greet from "./greet";
console.log(greet("Ada"));What `esModuleInterop` changes
CJS has no default export. When TypeScript compiles an ESM-style default import to require(), the result must still be the module.exports value. Two settings handle this, and they do different jobs:
allowSyntheticDefaultImportsis a type-check setting only. It lets you writeimport x from "cjs-module"without a type error. It changes no emitted code.esModuleInteropturns onallowSyntheticDefaultImportsand also emits helper functions so the code works at runtime.
With "module": "commonjs" and esModuleInterop on, this import:
import greet from "./greet";
greet("Ada");compiles to code like this:
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const greet_1 = __importDefault(require("./greet"));
(0, greet_1.default)("Ada");The helper checks the __esModule flag. TypeScript sets that flag on every CJS file it emits from ESM syntax. If the required module has the flag, it already has a real default and is used as is. If it does not, the helper wraps module.exports as { default: module.exports }. That wrapping is why the default import yields the function itself.
import * as ns from "cjs-module" is handled by a similar helper, __importStar, which copies the module's own properties onto a fresh object and adds default. One consequence: a namespace import of a module that exports a function is not callable under esModuleInterop. This is deliberate, because a real ES namespace object is never callable.
Defaults in modern settings
esModuleInterop is on by default when module is node16, nodenext, or preserve. In a new Node.js project you rarely set it by hand. You will still meet it in older commonjs projects, where leaving it off is a frequent source of confusion.
Common errors and what they mean
- TS1259: "can only be default-imported using the esModuleInterop flag". You wrote
import x from "m"for anexport =module without interop. EnableesModuleInteropor useimport x = require("m"). - Runtime
TypeError: x is not a function. Often caused byimport * as x from "m"on a module that exports a function. With interop on, the namespace object is not callable. Use the default import. undefinedon a default import at runtime. The compiled output and the runtime disagree about whether the module has adefault. This happens when a bundler, Node.js, andtsceach apply interop differently. Check that all of them are configured for the same behavior.- Named import from CJS fails only in Node.js ESM. Node.js could not detect the name statically. Import the default and read the property.
- Missing file extension. Relative imports in Node.js ESM need the extension, for example
./math.js, even though the source file ismath.ts. TypeScript does not rewrite it for you.
A practical checklist
- For a new Node.js project, write ESM, set
"type": "module", and use"module": "nodenext". - Use default imports for CJS dependencies, then read named values from the result.
- Use dynamic
import()when a CJS file must load an ESM-only package. - Describe CJS single-value modules in
.d.tsfiles withexport =. - Do not enable
allowSyntheticDefaultImportsalone for a Node.js project. It silences the checker without making the emitted code work.
Exercise
Your tsconfig.json sets "module": "commonjs" and does not set esModuleInterop. A dependency's .d.ts file uses export = greet, where greet is a function. You write import greet from "greet-lib" and get TS1259. Give two ways to fix it, and say what the first one changes in the emitted JavaScript.
Show answer
Option 1: set "esModuleInterop": true. The compiler then emits an _importDefault helper, which wraps module.exports as { default: module.exports } when the module lacks the _esModule flag. Your default import then resolves to the function itself. Option 2: change the import to import greet = require("greet-lib"), which compiles to a plain require() call and needs no helper. Setting only allowSyntheticDefaultImports would remove the error but emit no helper, so greet could be undefined at runtime.
Exercise
A CommonJS file named report.cts needs to use a package that ships only ES modules, on a Node.js version that cannot require() ES modules. What do you write, and why does a static import not work?
Show answer
Use dynamic import inside an async function, for example const { render } = await import("esm-only-pkg");. A static import in a CJS file is compiled to require(), and older Node.js versions throw ERRREQUIREESM when require() meets an ES module. TypeScript reports this as TS1479. Dynamic import() is allowed from CJS and returns a promise.