What Is the Difference Between CommonJS and ES Modules in Node.js?
When working with Node.js, you’ve probably encountered two types of module systems: CommonJS (CJS) and ES Modules (ESM). While both serve the purpose of enabling modular code, they differ significantly in syntax, functionality, and usage.
This guide will explain the differences between these two module systems, when to use each, and how they impact your Node.js projects.
1. What Are CommonJS and ES Modules?
CommonJS (CJS)
• The default module system in Node.js since its inception.
• Uses require for importing modules and module.exports or exports for exporting.
• Synchronous loading of modules.
Example of CommonJS:
// Exporting (math.js)
module.exports.add = (a, b) => a + b;
// Importing (index.js)
const math = require('./math');
console.log(math.add(2, 3)); // Output: 5
ES Modules (ESM)
• Introduced in JavaScript ES6 (2015) and adopted by Node.js in version 12 as an alternative module system.
• Uses import and export keywords.
• Supports asynchronous module loading.