JavaScript Answers

How to use module.exports as a constructor with Node.js?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *