JavaScript Modules (CommonJS)

 JavaScript Modules (CommonJS)


CommonJS is a module system for JavaScript that allows you to organize code into reusable modules using the require and module.exports syntax.



// math.js

exports.add = function(a, b) {

  return a + b;

};


exports.subtract = function(a, b) {

  return a - b;

};


// main.js

const math = require('./math');


console.log(math.add(5, 3)); // Output: 8

console.log(math.subtract(10, 4)); // Output: 6

In the example above, the math.js file exports two functions (add and subtract) using the exports object. In the main.js file, the require function is used to import the math module, and you can access its exported functions.

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...