📦 What Are They?
System | Description |
|---|---|
CommonJS | Module system used in Node.js (since early days). Synchronous loading. |
ES6 Modules | Modern module system introduced in ECMAScript 2015 (ES6). Native browser & Node.js support. |
✅ Syntax Comparison : Example 1
🔹 CommonJS (Used in Node.js)
// utils.js
function add(a, b) {
return a + b;
}
module.exports = add;// app.js
const add = require('./utils');
console.log(add(2, 3)); // 5✴️ ES6 Modules (Modern JS – Browser & Node.js)
// utils.js
export function add(a, b) {
return a + b;
}// app.js
import { add } from './utils.js';
console.log(add(2, 3)); // 5✅ Syntax Comparison : Example 2
✨ CommonJS:
// math.js
function add(a, b) { return a + b; }
function sub(a, b) { return a - b; }
module.exports = { add, sub };// app.js
const math = require('./math');
console.log(math.add(1, 2)); // 3✴️ ES6 Modules (Modern JS – Browser & Node.js)
// math.js
export function add(a, b) { return a + b; }
export function sub(a, b) { return a - b; }// app.js
import { add, sub } from './math.js';
console.log(add(1, 2)); // 3🔁 Key Differences
Feature | CommonJS | ES6 Modules (ESM) |
|---|---|---|
Introduced In | Node.js (default module system) | ECMAScript 2015 (ES6) |
Syntax |
|
|
Loading Type | Synchronous (blocking) | Asynchronous (non-blocking) |
Used In | Node.js (v12 and below by default) | Modern Browsers & Node.js (v13+ with |
File Extension |
|
|
Dynamic Imports | Not supported (require is static) | Supported via |
Top-Level | ❌ Not supported | ✅ Supported in ESM |
Export Format | Single or multiple via | Named or default via |
🧠 Pros and Cons
✅ CommonJS
✔ Simple to use in Node.js
✔ Mature and widely supported
❌ Not suitable for browser environments
❌ No native support for asynchronous module loading
✅ ES6 Modules
✔ Standardized in ECMAScript
✔ Works in both browser & server
✔ Supports tree-shaking (smaller bundle size)
✔ Asynchronous by nature
❌ Requires build tools or flags in older environments
💡 Use Case Recommendations
Use Case | Recommended System |
|---|---|
Node.js with legacy code | CommonJS |
Front-end browser development | ES6 Modules |
Full-stack (modern Node.js + front-end) | ES6 Modules |
Library authors targeting old Node.js | CommonJS |