Junior — Middle
Can you explain what the CommonJS modular system in JavaScript is?
sobes.tech AI
Answer from AI
CommonJS is a specification for a modular system for JavaScript, widely used in the Node.js environment. It allows breaking down code into separate files (modules), each exporting its functions, objects, or values, which other modules can then import.
Main features of CommonJS:
- Uses a synchronous module loading mechanism via the
require()function. - Each file is a separate module with its own scope.
- Exporting values is done through the
module.exportsobject.
Example of using CommonJS:
// math.js
function add(a, b) {
return a + b;
}
module.exports = { add };
// app.js
const math = require('./math');
console.log(math.add(2, 3)); // 5
Thus, CommonJS provides a convenient way to organize code and reuse modules in Node.js.