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 = ... and const x = require(...);. ES modules preserve export and import.
  • Runtime: Node.js requires .mjs or "type": "module" to run ES modules natively.
  • Interoperability: esModuleInterop and allowSyntheticDefaultImports help import ES modules from CommonJS and vice versa.
  • Top-level await: Only available when module is set to ESNext or NodeNext.

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.