ES6 Modules vs. CommonJS
JavaScript has two major module systems: ES6 Modules (ESM) and CommonJS (CJS). Understanding the differences is crucial for modern JavaScript development, especially when working with Node.js and bundlers.
1. Syntax Comparison
CommonJS (CJS)
Used primarily in Node.js. Uses require() and module.exports.
// export
module.exports = {
add: (a, b) => a + b
};
// import
const { add } = require('./math');
ES6 Modules (ESM)
The official standard for JavaScript. Uses import and export.
// export
export const add = (a, b) => a + b;
// import
import { add } from './math.js';
2. Key Differences
| Feature | CommonJS (CJS) | ES6 Modules (ESM) |
|---|---|---|
| Loading | Synchronous | Asynchronous |
| Resolution | Dynamic (Runtime) | Static (Compile-time) |
| Tree Shaking | Difficult/Impossible | Supported (Unused code removal) |
| Scope | this refers to exports |
this is undefined |
| Top-level await | Not supported | Supported |
| Strict Mode | Optional (default off) | Always enabled implicitly |
3. Dynamic vs. Static
CommonJS is dynamic. You can require modules conditionally.
if (user.isAdmin) {
const adminRoutes = require('./admin'); // Works in CJS
}
ESM is static. Imports must be at the top level. To load conditionally, you must use the dynamic import() function, which returns a Promise.
if (user.isAdmin) {
import('./admin.js').then(module => {
// ...
});
}
programming/javascript/vanilla/javascript programming/javascript/vanilla/modules