To use module.exports as a constructor with Node.js, we export it as a default export.
For instance, we write
class Square {
constructor(width) {
this.width = width;
}
area() {
return Math.pow(this.width, 2);
}
}
module.exports = Square;
to export the Square
class in square.js.
Then we write
const Square = require("./square");
const s = new Square(5);
const area = s.area();
to import the Square
constructor from square.js with require
.
And then we call Square
and use its methods.