Sometimes, we want to properly export an ES6 class in Node.js.
In this article, we’ll look at how to properly export an ES6 class in Node.js.
How to properly export an ES6 class in Node.js?
To properly export an ES6 class in Node.js, we can set the class as the value of module.exports in a module.
For instance, we write
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 in person.js.
Then we write
const Person = require("./person.js");
const someone = new Person("First name", "Last name");
someone.display();
to import the class with
const Person = require("./person.js");
And then we create a Person object and call the display method.
Conclusion
To properly export an ES6 class in Node.js, we can set the class as the value of module.exports in a module.