Modules: CommonJS vs ES Modules
Node.js supports two module systems: CommonJS (require, module.exports) and ES modules (import, export). Interviewers ask how they differ in loading, caching and interop, because mixing them causes real errors.
What you will learn
- Compare require and import
- Know how Node.js decides which system a file uses
- Explain module caching and circular dependencies
Key concepts
CommonJS
require() loads synchronously and returns module.exports. It runs at call time, so you can require conditionally. __dirname and __filename are available.
ES modules
import is static and analysed before the code runs, which allows tree shaking and top-level await. Exports are live bindings. Use import.meta.dirname and import.meta.filename (Node.js 20.11+).
How Node.js decides
.mjs is ESM, .cjs is CommonJS, and .js follows "type" in the nearest package.json ("module" or "commonjs").
Module cache
A module runs once; later imports or requires get the cached result. That is why a module-level db client acts like a singleton.
Step by step
Interop rules
- ESM can import CommonJS (module.exports becomes the default export)
- CommonJS can load ESM with await import(); newer Node.js versions also allow require() of ESM without top-level await
- Prefer ESM for new code; publish dual packages with the "exports" field when you must support both
Examples
Same module, both styles
// math.cjs
const add = (a, b) => a + b
module.exports = { add }
// math.mjs
export const add = (a, b) => a + b
// app.mjs
import { add } from './math.mjs'
import cjs from './math.cjs'
console.log(add(1, 2), cjs.add(1, 2))Practise it
Try these without looking back. If you can explain each one out loud, you are ready for this question.
- Create a circular dependency in CommonJS and explain why one side sees an empty object.
- Convert a small CommonJS project to ESM and list every change you needed.
Interview questions
What interviewers ask next on this topic. Answer out loud first, then open the model answer.
What is a live binding?
An ES module import is a read-only view of the exported variable, not a copy. If the exporting module changes the value, importers see the new value. CommonJS gives you a copy of whatever was in module.exports at require time.
Why can ESM do tree shaking and CommonJS cannot easily?
import and export are static syntax at the top level, so bundlers know exactly what is used before running any code. require can be called with any expression at any time, so a bundler cannot be sure.
Summary
CommonJS is synchronous and dynamic; ESM is static, async-ready and the standard. File extension and package.json "type" decide which one Node.js uses, and modules are cached after the first load.
Stuck on this one? Talk to Sumit.
Keys: F focus mode · ← → previous / next topic · Esc leave focus