Skip to the page

Modules, errors and memory · mid

ES modules vs CommonJS

ES modules use static import and export that are linked before code runs (enabling tree shaking, live bindings and top-level await), while CommonJS require runs synchronously at runtime and returns the module.exports object; current Node can require() most ES modules.

The notes

What you must know

  • ESM: static structure, imports are hoisted, strict mode, top-level this is undefined, live bindings (importers see updated exported let values), import.meta, top-level await, and dynamic import() that returns a promise (code splitting).
  • CommonJS: require() at runtime, synchronous, returns module.exports (exports is only a shortcut to it), has __dirname, and is cached after the first require.
  • Tree shaking needs static ESM imports and modules without side effects ('sideEffects': false in package.json). CommonJS defeats it.
  • Interop: importing CommonJS from ESM gives module.exports as the default export; default vs named confusion; 'type': 'module', .mjs/.cjs and the package 'exports' field.
  • Node can load ES modules with require() (except modules that use top-level await). Check the Node docs for your version.
  • Circular imports: ESM live bindings can hit the TDZ (ReferenceError); CommonJS returns a partly filled exports object.
  • In browsers <script type='module'> is deferred by default, fetched with CORS, and runs once per URL.

The red pen

Common traps: mistake → fix

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

    Fix: loading time, bindings and tree shaking differ.

  • Mistake: Imports copy values

    Fix: ESM imports are live, read-only views of the exporter's variables.

  • Mistake: import() works only in ESM files

    Fix: it works in CommonJS too and returns a promise.

Easy to hard

Questions interviewers ask, easy to hard

  1. What are the differences between CommonJS and ES modules?
  2. What is a live binding? Show one.
  3. Why does ESM enable tree shaking?
  4. How do you load an ES module from CommonJS in Node today?
  5. What is the dual-package hazard, and how do circular dependencies behave in each system?

Practise

Practise with these questions

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