TypeScript Reference ยท tsconfig: Language, Modules and Emit Options
TypeScript esModuleInterop option
Reference for esModuleInterop: why import fs from 'fs' needs it, how namespace and default imports of CommonJS modules behave, and what changed in newer versions.
CommonJS modules export a single value with module.exports = .... ES modules have a default export and named exports. esModuleInterop makes TypeScript's emitted code, and its type checking, treat a CommonJS module's module.exports as the default export when you write import x from "cjs-module", and fixes how import * as x behaves for modules that export a function or class.
It does this by emitting small helpers (__importDefault, __importStar) when compiling to CommonJS, and it turns on allowSyntheticDefaultImports for the type checker. In Node's native ESM mode (module: nodenext) the runtime already behaves this way, and in recent TypeScript versions the interop is always on and cannot be switched off.
import path from "node:path"; // default import of a CommonJS module import * as os from "node:os"; // namespace import
Try it
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.
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.
Syntax
{ "compilerOptions": { "esModuleInterop": true } }
| Part | Description |
|---|---|
| Type | boolean. Recommended: true. In recent releases it is effectively always on. |
| Command line | tsc --esModuleInterop |
| Implies | allowSyntheticDefaultImports: true |
| Emit | With module: commonjs, adds __importDefault and __importStar helpers (or uses importHelpers). |
Usage notes
- Without interop,
import fs from "fs"was an error in type-checking and, if forced, producedundefinedat runtime for CommonJS modules, because thedefaultproperty did not exist. The old workaroundimport * as fs from "fs"still works. import * as xwith interop returns a namespace object, not the function itself. Callingx()on it for amodule.exports = functionmodule is an error under interop, as it is in real ES modules.- The helpers copy the module's own properties into a namespace object, so changes to the original after import may not appear (live bindings are not kept for CommonJS).
- In Node ESM,
import x from "cjs"givesmodule.exports; named imports work only for names Node can detect statically in the CommonJS file. - Bundlers do their own interop; keep the option on so type-checking agrees with them.
- Keep it together with
module,moduleResolutionandverbatimModuleSyntaxchoices in the tsconfig lesson.