These are JavaScript's two module systems for splitting code across files.
ES Modules (ESM) — the modern standard
js
// import / export, used in browsers and modern Node
import { sum } ;
defaultThing ;
x = ;
() {};
These are JavaScript's two module systems for splitting code across files.
// import / export, used in browsers and modern Node
import { sum } ;
defaultThing ;
x = ;
() {};
const { sum } = require("./math");
module.exports = { x: 1 };
| ES Modules | CommonJS | |
|---|---|---|
| Syntax | import/export | require/module.exports |
| Loading | static, async | dynamic, synchronous |
| Analyzable | ✅ → tree-shaking | ❌ harder |
| Bindings | live (read-only) | a copied value |
this at top | undefined | module.exports |
Static means ESM imports are known at parse time, which lets bundlers do tree-shaking (drop unused exports). CommonJS require is dynamic (you can require conditionally), so it can't be analyzed as easily.
{ "type": "module" } // in package.json, or use the .mjs extension
You can't require() an ESM-only package from CommonJS; mixing the two has rough edges. ESM imports are also live bindings — if the exporter changes the value, importers see the new value (CJS gives you a snapshot copy).
ESM is the future (browser-native, tree-shakeable, top-level await).
Prefer it for new code; understand CJS because much of the Node ecosystem still uses it.
A library of IT interview questions with detailed answers — from Junior to Senior.
Donate