Skip to content
Tutorials Center
My learning

Topics

Lesson 49 of 96 ยท Modules and Declarations

CommonJS Interop and esModuleInterop

Understand CommonJS and ES module interop in TypeScript - esModuleInterop, allowSyntheticDefaultImports, import = require, export = and how default imports of CJS packages really work.

JavaScript has two module systems. ES modules (ESM) use import and export. CommonJS (CJS) is Node's original system: require() to load, module.exports to share. A huge amount of npm still ships as CommonJS, and TypeScript projects must talk to it. The rules for that conversation are called interop, and they cause some of the most confusing errors in the language, such as "This module can only be default-imported using the 'esModuleInterop' flag".

This lesson explains the difference at runtime, what the interop flags do, the TypeScript-only syntax import x = require() and export =, and the settings to choose for a new project. It builds on Modules and Declaration Files.

Two module shapes

A CommonJS module hands out a single value, whatever you assign to module.exports. It could be a function, a class or an object. An ES module hands out a namespace of named exports and, optionally, one special export called default.

TypeScript What import actually returns for a CommonJS file

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

When Node's ESM loader imports a CommonJS file, it always puts the whole module.exports value on default. It also tries to detect named exports by scanning the file (that is why configModule.port works for exports.port = 8080), but that detection is a heuristic and misses many patterns. The only reliable handle is default.

(Recent Node versions also add a string export named module.exports that holds the same value, which you can see in the Object.keys line above. Ignore it in everyday code.)

That is the first thing to remember: in real Node ESM, the default import of a CJS module is module.exports.

Why TypeScript needed esModuleInterop

TypeScript's CommonJS emit and many bundlers once treated things differently: for the module module.exports = greet, the code import greet from './greet' compiled to require('./greet').default, which is undefined, because a plain function has no default property. People worked around it with the awkward form import * as greet from './greet', and then called the namespace, which is technically illegal for a real ES module namespace.

esModuleInterop fixes this by emitting small helper functions that make CommonJS behave like ESM:

  • __importDefault(mod) returns mod if it is already an ES module (mod.__esModule is true), or wraps it as { default: mod }. That makes import x from 'cjs' give you module.exports.
  • __importStar(mod) builds a namespace object that copies the named properties and sets default to the whole mod.

You can see the idea in a few lines:

TypeScript The helpers behind esModuleInterop, rewritten by hand

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

You never write these helpers yourself. The point is that esModuleInterop is a compile-time and emit-time feature: it changes what code TypeScript generates for CommonJS output. When your code runs as real ESM (Node with "type": "module"), or goes through a bundler, the runtime or bundler already does the equivalent.

The two flags

Flag What it changes Affects emit?
allowSyntheticDefaultImports Lets the type checker accept import x from 'cjs' when the module has no real default export No, types only
esModuleInterop Emits __importDefault and __importStar helpers and turns on allowSyntheticDefaultImports Yes

If you write only allowSyntheticDefaultImports, the compiler stops complaining, but the emitted require(...).default may be undefined at runtime. That mismatch is why you should not set it without esModuleInterop unless a bundler does the interop.

Today you rarely set either by hand. With "module": "nodenext" (or node16), TypeScript follows Node's real rules and esModuleInterop behavior is on. Most project templates also enable it. If you inherit an old config that disables it, you will see namespace-style imports (import * as express from 'express') throughout the code. Those still work when interop is on, with one catch described next.

Namespace import of a callable module

With interop on, import * as x from 'cjs' gives you a namespace object, not the function. Calling it fails at compile time:

TypeScript
import * as express from 'express';
const app = express();
// error TS2349: This expression is not callable.
//   Type 'typeof import("express")' has no call signatures.

The fix is a default import:

TypeScript
import express from 'express';
const app = express(); // works with esModuleInterop or nodenext

For modules that export an object of named functions, both the default import and the named import styles work:

TypeScript
import { join } from 'node:path';     // named import
import path from 'node:path';         // default import: the whole module.exports

import = require and export =

TypeScript has its own syntax that maps one-to-one to CommonJS. It exists for modules where one value is the whole export.

TypeScript
// utils.cts, a CommonJS TypeScript file
function slugify(text: string): string {
  return text.toLowerCase().replace(/\s+/g, '-');
}
slugify.separator = '-';

export = slugify;            // module.exports = slugify
TypeScript
// main.cts
import slugify = require('./utils.cjs');   // const slugify = require('./utils.cjs')

console.log(slugify('Hello World'));

Rules to know:

  • export = cannot coexist with other export statements in the same file, because there is only one module.exports.
  • import x = require() is only allowed in files compiled as CommonJS (.cts files, or .ts files when the package is not "type": "module"). In ES module files it is an error (TS1202).
  • export = is not erasable syntax: Node's built-in type stripping rejects it. See Node and TypeScript.
  • Declaration files for old packages use export = heavily. When you see export = Foo in a .d.ts and the package works with import Foo from 'pkg', that is interop at work.

If you are writing new code, prefer ES import and export everywhere. Use export = and import = require() only when a file must be CommonJS, or when you need to model an existing package in a .d.ts file.

Loading CommonJS from an ES module on purpose

Inside an ES module there is no require. When you need CommonJS behavior (loading JSON, or an old package), use createRequire:

TypeScript createRequire gives an ES module a typed require

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

require returns any, so annotate the result with typeof import('...') to keep type safety. The last line shows an ES module has no module of its own: typeof module is "undefined".

Choosing settings for a new project

Situation Settings
New Node.js app or library "module": "nodenext", "type": "module" in package.json, ES import syntax everywhere
Front-end app with a bundler (Vite, esbuild) "module": "esnext" or "preserve", "moduleResolution": "bundler"
Old CommonJS app you cannot convert "module": "commonjs" or .cts files, with esModuleInterop on
A tricky package that will not default-import Check its .d.ts: export = means default import needs interop; export default means it works anywhere

When an import fails, ask three questions. What does the package really export at runtime (look at module.exports or its package.json exports)? What does its .d.ts claim? And which of those two systems is my own file using (check package.json "type" and the file extension)? The error always comes from a mismatch between two of the three.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. When Node's ESM loader imports a CommonJS file, what does the default export contain?

    default is the whole module.exports value, so a function or class export comes through intact.
  2. 2. What does esModuleInterop do that allowSyntheticDefaultImports alone does not?

    allowSyntheticDefaultImports only affects type checking. esModuleInterop also changes emit and turns that flag on.
  3. 3. With interop enabled, why is import * as express from 'express'; express() an error?

    Use import express from 'express' so you get module.exports, the callable function.
  4. 4. Where is import fs = require('node:fs') allowed?

    It maps to require, which exists only in CommonJS output. In an ES module it is error TS1202.
  5. 5. How do you get a typed require inside an ES module?

    createRequire from node:module returns a working require; it returns any, so you add the type yourself.

Summary

  • CommonJS exports one value with module.exports; ES modules export a namespace plus an optional default. Node puts the whole module.exports on default.
  • esModuleInterop emits helpers so import x from 'cjs' gives module.exports; allowSyntheticDefaultImports only relaxes type checking.
  • Use default imports for callable CommonJS modules; a namespace import cannot be called.
  • export = and import x = require() map directly to CommonJS, work only in CommonJS files and are not erasable syntax.
  • In an ES module use createRequire when you really need require, and annotate the result with typeof import().
  • For new code, write ES modules with nodenext or a bundler setup, and diagnose failures by comparing the runtime export, the .d.ts and the importing file's module type.

Next: Declaration Files