"esModuleInterop"

Makes it easier to import CommonJS packages with ES module syntax.

On this page

Example

#
JSON
{
  "compilerOptions": {
    "esModuleInterop": true,
    "module": "CommonJS"
  }
}

Definition and usage

#

Many older npm packages are written in CommonJS (module.exports = …). The esModuleInterop option lets you import them with the ordinary syntax import express from "express", instead of import * as express from "express".

The compiler then adds small helper functions to the generated code, which behave the way bundlers and Node.js do when joining the two module systems.

Enabling esModuleInterop also automatically enables allowSyntheticDefaultImports, which allows a default import from a module with no default export at the type-checking stage.

Syntax

#
Syntax
"esModuleInterop": true

More examples

#
Importing a CommonJS package
TypeScript
// with esModuleInterop
import express from 'express'

// without esModuleInterop you had to write:
// import * as express from 'express'

Good practices

#
  • In new projects, leave esModuleInterop on. It’s the default in tsc --init templates.
  • If a default import returns undefined at runtime, check this option and the package’s module format.

Related entries

#

Spotted a mistake or missing an example? Write to us.