Skip to the page

Modules and packages · mid

CommonJS vs ES modules in Node

CommonJS loads modules synchronously with require and module.exports at run time, while ES modules use static import/export that is read before the code runs, load asynchronously and give live bindings; Node chooses by file extension and the nearest package.json "type".

The notes

What you must know

  • .mjs is always ESM and .cjs is always CommonJS. A .js file follows the nearest package.json "type" ("module" or "commonjs"); with no type, current Node also detects ESM syntax.
  • CommonJS wraps each file in a function (exports, require, module, __filename, __dirname). require is synchronous and cached in require.cache by resolved path. exports = {...} exports nothing: use module.exports.
  • ESM: import/export are static, so bundlers can tree-shake; top-level await works; there is no __dirname (use import.meta.dirname / import.meta.filename); relative imports need the file extension.
  • Interop: ESM can import CommonJS (the default import is module.exports). CommonJS can require() an ES module in current Node (unflagged in 22.12 and 20.19, no longer experimental in 25.4) if its graph has no top-level await; otherwise you get ERR_REQUIRE_ASYNC_MODULE and must use await import().
  • A module runs once; later imports get the same instance. That makes a module a cheap singleton (one DB pool), and it is why circular requires see a half-filled exports object.
  • ESM bindings are live (an exported let that changes is seen by importers); CommonJS gives you the value that was on module.exports when you read it.

The red pen

Common traps: mistake → fix

  • Mistake: ESM and CommonJS are the same thing with different syntax

    Fix: they differ in loading (sync vs async), timing (static vs run time), bindings and file resolution.

  • Mistake: You can never require an ES module

    Fix: current Node can require() a synchronous ES module; only top-level await blocks it.

  • Mistake: exports = { a } works like module.exports = { a }

    Fix: reassigning exports only changes a local variable.

Easy to hard

Questions interviewers ask, easy to hard

  1. What are the differences between CommonJS and ES modules?
  2. How does Node decide whether a .js file is ESM or CommonJS?
  3. How do you get __dirname in an ES module?
  4. What happens with circular dependencies?
  5. Can a CommonJS app use an ESM-only package today? What are the limits?

Practise

Practise with these questions

Explain it out loud

Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.

Practise by voice

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview