CommonJS
CommonJS Modules․ require and module.exports
CommonJS is a module system primarily designed for the Node.js environment. It allows splitting code into smaller files and reusing them across different parts of an application. CommonJS became the de-facto standard for Node.js applications and was widely adopted before the introduction of ES Modules (ESM).
In CommonJS, each file is a separate module with its own scope. A module can export data, functions, or objects, which can then be imported into other files.
In CommonJS, the require()
function is used to import modules, while the module.exports
object is used for exporting.
// greet.js file
function greet(name) {
return `Hello, ${name}!`;
}
module.exports = greet;
// main.js file
const greet = require('./greet');
console.log(greet('Ani')); // Hello, Ani!
As we can see, the greet.js
file exports the greet
function via module.exports
, and main.js
imports it using the require()
function.
CommonJS provides two ways to export: module.exports
and exports
. Initially, exports
is just a reference to module.exports
. However, caution is required:
// EXAMPLE: Correct usage
exports.greet = function(name) {
return `Hello, ${name}!`;
};
// EXAMPLE: Incorrect usage
exports = function(name) {
return `Hello, ${name}!`;
};
In the second example, the exports
reference is reassigned to a new function, and Node.js won’t know what to export. Therefore, if you want to export the entire module, always use module.exports
.
require()
function imports modules synchronously.require()
calls return the same object.CommonJS was the first widely adopted module system in JavaScript. It works exceptionally well in Node.js and remains a crucial part of server-side applications. In the next article, we’ll explore ES Modules—the modern, official module system for JavaScript.