bredom
7/18/2018 - 11:02 PM

Node.js module.exports

How to use module.exports

// calculator.js

module.exports.add = (a,b) => a+b

// app-use-calculator.js

const calculator = require('./calculator.js')
console.log(calculator.add(2,2)) // prints 4

/////////////////////////////////////////////
//You can attach a class to it
// calculator-base.js

module.exports = class Calculator {
  add(a,b) { return a + b }
  substract(a,b) { return a - b }
}

// calculator-advanced.js

const Calculator = require('./calculator-base.js')

class AdvancedCalculator extends Calculator {
  multiply(a,b) { return a * b }
  divide(a,b) { return a / b }
}

module.exports = new AdvancedCalculator()

// app-use-advanced-calculator.js

const calculator = require('./calculator-advanced.js')

console.log(calculator.add(2,2)) // prints 4
console.log(calculator.multiply(3,3)) // prints 9

//Couple good and bad examples
// good
module.exports = {
  add(a,b) { return a+b }
}

// good
module.exports.subtract = (a,b) => a-b

// valid
exports = module.exports

// good and simply a shorter version of the code above
exports.multiply = (a,b) => a*b

// bad, exports is never exported
exports = {
  divide(a,b) { return a/b }
}