What is the difference between ESModule and CommonJS in TS config
· Category: TypeScript
Short answer
module: "CommonJS" emits require and module.exports for Node.js compatibility. module: "ESNext" or "NodeNext" preserves import/export syntax for modern bundlers and Node.js ESM.
Key differences
- Output syntax: CommonJS produces
exports.foo = ...andconst x = require(...);. ES modules preserveexportandimport. - Runtime: Node.js requires
.mjsor"type": "module"to run ES modules natively. - Interoperability:
esModuleInteropandallowSyntheticDefaultImportshelp import ES modules from CommonJS and vice versa. - Top-level await: Only available when
moduleis set toESNextorNodeNext.
When to use each
- Use CommonJS for legacy Node.js tools and libraries.
- Use ES modules for modern applications, tree-shaking with bundlers, and isomorphic code.