CommonJs (Node.js) - Module.exports

> (World Wide) Web - (W3|WWW) > Javascript (Js|ECMAScript)

1 - About

If you want the commonJs module to be an instance of some class, assign the desired export object to the module.exports property.

Note that assigning the desired object to exports will simply rebind the local exports variable, which is probably not what is desired.

Advertising

3 - Example and Usage

The module.exports property can be assigned a new value (such as a function or object).

square.js
// assigning to exports will not modify module, must use module.exports
module.exports = (width) => {
  return {
    area: () => width ** 2
  };
};
main.js
const square = require('./square.js');
const mySquare = square(2);
console.log(`The area of my square is ${mySquare.area()}`);

4 - Documentation / Reference

web/javascript/module.exports.txt · Last modified: 2019/02/16 17:40 by gerardnico