CommonJS vs ES Modules
1. Definition
CommonJS and ES Modules are two module systems used in Node.js to organize and reuse code. CommonJS is the traditional module system, while ES Modules (ESM) is the modern standard introduced in JavaScript.
2. CommonJS
- Uses require() to import modules
- Uses module.exports to export
- Synchronous loading
- Default module system in Node.js
3. ES Modules (ESM)
- Uses import to import modules
- Uses export / export default
- Asynchronous loading
- Modern JavaScript standard
4. Key Differences
- Syntax: require() vs import
- Export: module.exports vs export
- Loading: Sync vs Async
- Usage: Older vs Modern
5. Example
👉 CommonJS
// math.js
module.exports = function add(a, b) {
return a + b;
};
// app.js
const add = require("./math");
console.log(add(2, 3));👉 ES Modules
// math.js
export function add(a, b) {
return a + b;
}
// app.js
import { add } from "./math.js";
console.log(add(2, 3));6. When to Use
- Use CommonJS in older Node.js projects
- Use ES Modules in modern applications
- Prefer ES Modules for frontend and full-stack apps
7. Advantages
- CommonJS is simple and widely supported
- ES Modules provide cleaner syntax
- Better compatibility with modern tools