4 min read
•Question 4 of 62easyWhat is the difference between CommonJS and ES Modules?
Understanding module systems in Node.js.
What You'll Learn
- CommonJS syntax
- ES Modules syntax
- Key differences
CommonJS (CJS)
code.jsJavaScript
// Exporting
module.exports = { add, subtract };
// or
exports.add = add;
// Importing
const { add } = require('./math');
const fs = require('fs');ES Modules (ESM)
code.jsJavaScript
// Exporting
export const add = (a, b) => a + b;
export default function subtract(a, b) { return a - b; }
// Importing
import { add } from './math.js';
import subtract from './math.js';
import * as math from './math.js';Key Differences
| Feature | CommonJS | ES Modules |
|---|---|---|
| Syntax | require/exports | import/export |
| Loading | Synchronous | Asynchronous |
| File Extension | .js, .cjs | .mjs or "type": "module" |
| Top-level await | ❌ No | ✅ Yes |
| Tree shaking | ❌ No | ✅ Yes |
Enabling ESM in Node.js
data.jsonJSON
// package.json
{
"type": "module"
}Or use .mjs file extension.
Interop
code.jsJavaScript
// Import CJS in ESM
import pkg from 'commonjs-package';
// Import ESM in CJS (dynamic import)
async function loadESM() {
const { add } = await import('./esm-module.mjs');
}