Lesson 52 of 55 · javascript
Modules – CommonJS vs ES Modules
Duration: 12 mins
Lesson 52 of 55 · javascript
Duration: 12 mins
import/export). Historically Node used CommonJS (require). Understanding both helps you work across environments.\n\n## 1️⃣ CommonJS (Node)\njs\n// math.cjs\nfunction mul(a,b){ return a*b; }\nmodule.exports = { mul };\n// app.cjs\nconst { mul } = require('./math.cjs');\nconsole.log(mul(3,4));\n\n* Synchronous, loaded at runtime.\n* Exports an object.\n\n## 2️⃣ ES Modules (Browser & Node)\njs\n// utils.js\nexport const sub = (a,b) => a-b;\nexport default function add(a,b){ return a+b; }\n// app.js (type=\"module\")\nimport add, { sub } from './utils.js';\nconsole.log(add(5,2), sub(5,2));\n\n* Static analysis – imports are hoisted.\n* Supports named and default exports.\n\n## 3️⃣ Using ES Modules in Node\n* Add \"type\": \"module\" to package.json, or use .mjs extension.\n* Interop:\njs\n// Import a CJS module from ESM\nimport pkg from './cjs-lib.cjs'; // `pkg` is the `module.exports` value.\n\n* Dynamic import in CJS:\njs\n(async () => {\n const {default: greet} = await import('./greet.mjs');\n greet();\n})();\n\n\n## 4️⃣ When to choose which?\n- Browser‑only code: use ES Modules (type=\"module\").\n- Existing Node projects: stay with CommonJS unless you need tree‑shaking or native ESM features.\n- New libraries: ship both (main for CJS, module for ESM) to maximise compatibility.\n\nUnderstanding both systems prevents unexpected undefined imports and makes your build pipeline smoother.\n