Advertisement
Intermediate TypeScript, Modules

What does the 'esModuleInterop' compiler option fix when importing CommonJS modules?

Short answer

Without esModuleInterop, importing a CommonJS module that exports a single function/value (via module.exports = x) using ES-style `import x from 'module'` syntax doesn't work correctly, because CommonJS and ES Modules have subtly incompatible default-export semantics…

Save TypeScript mock interview
Advertisement
AModel answer
Without esModuleInterop, importing a CommonJS module that exports a single function/value (via module.exports = x) using ES-style `import x from 'module'` syntax doesn't work correctly, because CommonJS and ES Modules have subtly incompatible default-export semantics; esModuleInterop adds compatibility shims so default imports 'just work' against CommonJS modules.
// Without esModuleInterop, this often fails or needs `import * as x`
// With esModuleInterop: true
import express from 'express'; // works cleanly, even though express uses module.exports
Real-world example
Enabling clean default-import syntax for Node.js libraries like express, lodash, or moment that use CommonJS's module.exports.
Likely follow-ups
  • What alternative, more verbose import syntax would you need without esModuleInterop enabled?
Related topics