How to properly export an ES6 class in Node 4?
// person.js'use strict';module.exports = class Person { constructor(firstName, lastName) { this.firstName = firstName; this.lastName = lastName; } display() { console.log(this.firstName + " " + this.lastName); }}
// index.js'use strict';var Person = require('./person.js');var someone = new Person("First name", "Last name");someone.display();
If you are using ES6 in Node 4, you cannot use ES6 module syntax without a transpiler, but CommonJS modules (Node's standard modules) work the same.
module.export.AspectType
should be
module.exports.AspectType
hence the error message "Cannot set property 'AspectType' of undefined" because module.export === undefined
.
Also, for
var AspectType = class AspectType { // ... };
can you just write
class AspectType { // ... }
and get essentially the same behavior.
With ECMAScript 2015 you can export and import multiple classes like this
class Person{ constructor() { this.type = "Person"; }}class Animal{ constructor() { this.type = "Animal"; }}module.exports = { Person, Animal};
then where you use them:
const { Animal, Person } = require("classes");const animal = new Animal();const person = new Person();
In case of name collisions, or you prefer other names you can rename them like this:
const { Animal : OtherAnimal, Person : OtherPerson} = require("./classes");const animal = new OtherAnimal();const person = new OtherPerson();