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.