CommonJS is a project aimed at defining a standard for modular programming in JavaScript. It was created to address the need for a consistent module system that could be used across different environments, particularly in server-side JavaScript. The most notable implementation of CommonJS is in Node.js, where it allows developers to organize their code into reusable modules.
At its core, CommonJS provides a simple way to define modules and manage dependencies. This is achieved through the use of the `require` function to import modules and the `module.exports` object to export functionality from a module. The design philosophy behind CommonJS emphasizes synchronous loading of modules, which is suitable for server-side applications where modules can be loaded from the local filesystem.
Here’s a simple example to illustrate how CommonJS modules work:
// math.js - A CommonJS module
function add(a, b) {
return a + b;
}
function subtract(a, b) {
return a - b;
}
// Exporting functions
module.exports = {
add: add,
subtract: subtract
};
In the above example, we define a module named `math.js` that exports two functions: `add` and `subtract`.
// app.js - Importing the CommonJS module
const math = require('./math');
console.log(math.add(5, 3)); // Output: 8
console.log(math.subtract(5, 3)); // Output: 2
In `app.js`, we import the `math` module using `require` and then call the exported functions.
CommonJS has played a significant role in shaping the way JavaScript modules are structured, particularly in server-side applications. By providing a clear and consistent module system, it has enabled developers to write modular, maintainable, and reusable code. While newer module systems like ES Modules (ESM) have emerged, understanding CommonJS remains crucial for working with existing Node.js applications and libraries.