Node.js Developer interview question · Most asked

What are the differences between CommonJS and ES modules in Node.js?

Summary

CommonJS uses require/module.exports, loads synchronously and is evaluated at runtime; ES modules use import/export, are statically analyzable, load asynchronously, support top-level await, and are strict mode by default. Node picks the format from .mjs/.cjs extensions or the package.json type field.

Longer Answer

ESM can import CommonJS (default import = module.exports). CommonJS can now require() synchronous ESM graphs in modern Node (22.12+/20.19+), but not ones using top-level await. In ESM, __dirname is replaced by import.meta.dirname/import.meta.filename (Node 20.11+). Packages use the exports field to define entry points and conditional exports for both formats.

Key Points

  • require vs import
  • type: module or .mjs/.cjs
  • Top-level await only in ESM
  • require(esm) supported in modern Node
  • exports field for package entry points

More most-asked Node.js Developer questions

← All Node.js Developer questions