CommonJS vs. ES Modules in JavaScript

6/29/2025

diagram Comparison table of CommonJS and ES Modules in JavaScript

Go Back

CommonJS vs. 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.


 diagram Comparison table of CommonJS and ES Modules in JavaScript

What is CommonJS?

CommonJS is the module system used by Node.js by default before ES Modules were natively supported.

Syntax Example:

// math.js (CommonJS)
const add = (a, b) => a + b;
module.exports = { add };

// app.js
const { add } = require('./math');
console.log(add(2, 3));

Key Features:

  • Uses require() to import

  • Uses module.exports to export

  • Synchronous loading

  • Best for Node.js (server-side)


What are ES Modules (ESM)?

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.

Syntax Example:

// math.js (ESM)
export const add = (a, b) => a + b;

// app.js
import { add } from './math.js';
console.log(add(2, 3));

Key Features:

  • 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")


Key Differences Between CommonJS and ES Modules

FeatureCommonJSES Modules (ESM)
Import Syntaxrequire()import
Export Syntaxmodule.exportsexport, export default
Load TypeSynchronousAsynchronous
Execution ContextWrapped in functionStrict mode module scope
CompatibilityDefault in Node.js pre-ESMDefault in browsers
File Extension.js.mjs or .js w/ config

Mixing CommonJS and ES Modules

Mixing the two can lead to issues. However, Node.js does support limited interop:

CommonJS importing ES Module (❌ not straightforward):

// Can't use import without extra config in CommonJS
const { add } = await import('./math.js');

ES Module importing CommonJS:

// Works, but you access the default export
import pkg from './utils.cjs';

 


Conclusion

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.

Table of content