CommonJS vs. ES Modules in JavaScript
commonjs-vs-esmodules.png: "Comparison table of CommonJS and ES Modules in JavaScript
When working with JavaScript—especially in different environments like Node.js or the browser—you'll encounter two major module systems: CommonJS (CJS) and ES Modules (ESM). Understanding the differences between them is crucial for writing modular, maintainable, and compatible code.
CommonJS is the module system used by Node.js by default before ES Modules were natively supported.
// math.js (CommonJS)
const add = (a, b) => a + b;
module.exports = { add };
// app.js
const { add } = require('./math');
console.log(add(2, 3));
Uses require()
to import
Uses module.exports
to export
Synchronous loading
Best for Node.js (server-side)
ES Modules (ESM) is the standardized module system introduced in ES6 (2015). It’s the preferred format for JavaScript in the browser and modern development.
// math.js (ESM)
export const add = (a, b) => a + b;
// app.js
import { add } from './math.js';
console.log(add(2, 3));
Uses import
/export
Supports named & default exports
Asynchronous loading (ideal for browsers)
Native support in modern browsers and Node.js (with .mjs
or type: "module"
)
Feature | CommonJS | ES Modules (ESM) |
---|---|---|
Import Syntax |
require() |
import |
Export Syntax |
module.exports |
export , export default |
Load Type | Synchronous | Asynchronous |
Execution Context | Wrapped in function | Strict mode module scope |
Compatibility | Default in Node.js pre-ESM | Default in browsers |
File Extension |
.js |
.mjs or .js w/ config |
Mixing the two can lead to issues. However, Node.js does support limited interop:
// Can't use import without extra config in CommonJS
const { add } = await import('./math.js');
// Works, but you access the default export
import pkg from './utils.cjs';
Both CommonJS and ES Modules are vital parts of JavaScript’s evolution. While CommonJS is deeply rooted in Node.js, ES Modules offer a future-proof, standard way to write modular code that works both in the browser and Node.
Adopting ES Modules is encouraged for new projects due to their cleaner syntax, async capabilities, and better compatibility across environments.