Categories
JavaScript Answers

How to properly export an ES6 class in Node.js?

Spread the love

To properly export an ES6 class in Node.js, we set the class as the value of module.exports.

For instance, in person.js, we write

"use strict";

module.exports = class Person {
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }

  display() {
    console.log(this.firstName, this.lastName);
  }
};

to export the Person class.

Then we write

const Person = require("./person.js");

const someone = new Person("First name", "Last name");
someone.display();

to require the person.js module and then create a Person instance.

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 *