Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly export an ES6 class in Node 4?

I defined a class in a module:

"use strict";

var AspectTypeModule = function() {};
module.exports = AspectTypeModule;

var AspectType = class AspectType {
    // ...    
};

module.export.AspectType = AspectType;

But I get the following error message:

TypeError: Cannot set property 'AspectType' of undefined
    at Object.<anonymous> (...\AspectType.js:30:26)
    at Module._compile (module.js:434:26)
    ....

How should I export this class and use it in another module? I have seen other SO questions, but I get other error messages when I try to implement their solutions.

like image 923
Jérôme Verstrynge Avatar asked Oct 04 '22 11:10

Jérôme Verstrynge


People also ask

Does node support ES6 classes?

Finally es6 classes have landed in Node.

Can you export classes in JavaScript?

Use named exports to export a class in JavaScript, e.g. export class Employee {} . The exported class can be imported by using a named import as import {Employee} from './another-file. js' . You can use as many named exports as necessary in a file.


2 Answers

// 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();
like image 155
sitrakay Avatar answered Oct 11 '22 15:10

sitrakay


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.

like image 135
loganfsmyth Avatar answered Oct 11 '22 15:10

loganfsmyth