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.
How CommonJS Works
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.
The Difference Between module.exports and exports
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.
Key Features of CommonJS Modules
- Synchronous Import — The
require()function imports modules synchronously. - Caching — Once a module is imported, it is cached, so subsequent
require()calls return the same object. - Primarily Used in Node.js — CommonJS is tightly coupled with Node.js’s server-side environment.
Limitations of CommonJS
- Does Not Work in Browsers — CommonJS modules are designed for servers and don’t work directly in browsers without bundlers (e.g., Webpack).
- Synchronous Nature — Modules in browsers should ideally be loaded asynchronously, but CommonJS does not support this natively.
Conclusion
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.