esModuleInterop: Bridging Module Systems
What you'll learn: How esModuleInterop makes importing CommonJS modules feel natural when using modern ES module syntax.
The Module System Clash
JavaScript has two major module systems: CommonJS (used in older Node.js code) and ES Modules (the modern standard). They handle default exports differently, creating friction when you try to import CommonJS modules using ES module syntax.
Without esModuleInterop, importing a CommonJS library like this:
import express from 'express';
...might fail or require awkward syntax like import * as express from 'express' because CommonJS doesn't have true default exports the way ES modules do.
What esModuleInterop Does
Think of esModuleInterop as a translator at a conference. When you speak in ES module language (using import something from), it automatically translates that into something CommonJS modules understand, and vice versa.
When you enable this option in tsconfig.json:
{
"compilerOptions": {
"esModuleInterop": true
}
}
TypeScript generates helper code that creates synthetic default exports for CommonJS modules. Now your clean, modern import syntax works seamlessly with older libraries.
Why This Matters
Most npm packages were written using CommonJS. Without esModuleInterop, you'd constantly switch between different import styles depending on how a library was written. This flag lets you use consistent, clean syntax across your entire codebase.
Key Takeaway: Enable esModuleInterop: true to write natural ES module imports (import X from 'library') that work smoothly with CommonJS packages, eliminating module system compatibility headaches.