Categories
JavaScript Answers

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

Spread the love

Sometimes, we want to use module.exports as a constructor with Node.js.

In this article, we’ll look at how to use module.exports as a constructor with Node.js.

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

To use module.exports as a constructor with Node.js, we export the constructor as a default export.

For instance, we write

class Square {
  constructor(width) {
    this.width = width;
  }
  area() {
    return this.width ** 2;
  }
}

export default Square;

to export the Square class as a default export with export default.

Then we import it by writing

import Square from "./square";

in another module in the same folder.

Conclusion

To use module.exports as a constructor with Node.js, we export the constructor as a default export.

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 *