CommonJS
CommonJS was the first module system introduced in JavaScript and is widely used in server-side environments, such as Node.js. It follows a synchronous approach to module loading, where modules are loaded and executed in a blocking manner. Here’s an example of how modules are imported and exported using CommonJS:
Module Export
// math.js
const add = (a, b) => a + b;
const subtract = (a, b) => a - b;
module.exports = {
add,
subtract
};
Module Import
// app.js
const math = require('./math.js');
console.log(math.add(5, 3)); // Output: 8
console.log(math.subtract(5, 3)); // Output: 2
In CommonJS, the module.exports
object is used to export values from a module,
and require
is used to import those values into another module. The imported
values are accessed through the math
object in the example above.
ESModule
ESModule is the module system introduced in ECMAScript 2015 (ES6) and is now widely supported by modern browsers. It follows an asynchronous approach to module loading, where modules are loaded and executed in a non-blocking manner. Here’s an example of how modules are imported and exported using ESModule:
Module Export
// math.js
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;
Module Import
// app.js
import { add, subtract } from './math.js';
console.log(add(5, 3)); // Output: 8
console.log(subtract(5, 3)); // Output: 2
In ESModule, the export
keyword is used to explicitly export values from a
module, and the import
statement is used to import those values into another
module. The imported values can be directly accessed in the example above
without using any additional object.
Key Differences
- Syntax: CommonJS uses module.exports and require for exporting and importing, respectively, while ESModule uses export and import statements.
- Loading Behavior: CommonJS modules are loaded synchronously, blocking the execution until all dependencies are loaded. ESModule modules are loaded asynchronously, allowing the rest of the code to continue executing while modules are being loaded.
- Browser Support: CommonJS is primarily used in server-side environments like Node.js, whereas ESModule is designed for browser-based JavaScript and is now widely supported by modern browsers.
It’s worth mentioning that both CommonJS and ESModule have their strengths and weaknesses, and the choice between them depends on the target environment and specific requirements of the project. Many projects nowadays leverage tools like Webpack or Babel to enable the usage of ESModule syntax while still maintaining backward compatibility with older systems that rely on CommonJS.
In conclusion, CommonJS and ESModule are two distinct module systems in JavaScript. While CommonJS is synchronous and primarily used in server-side environments, ESModule is asynchronous and widely supported in modern browsers. Understanding the differences between these module systems is essential for writing modular and maintainable JavaScript code.