Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js ES6 how to export class from module? [duplicate]

I'm trying to export an ES6 class from a CommonJS module in Node.js 6.2.0

class MyClass{
    //class contents here
}

exports = MyClass;

Then import it in another module:

var MyClass = require('/path/to/module.js')
var instance = new MyClass();

However I'm getting the following exception:

TypeError: MyClass is not a constructor

How can I properly do it?

Please note that I'm not using Babel/Tranceur it's pure JS as implemented in the latest Node 6.2.0 which according to Kangax implements ES6 in 93%.

//Edit: this is not a problem with exports vs module.exports. While using exports alone I'm getting some object with __proto__ set.

like image 687
kubal5003 Avatar asked May 23 '16 15:05

kubal5003


People also ask

How do I export a class object in node JS?

As we just saw, exporting a class can be accomplished by attaching the class as a property of the module. exports object. First, we created a class using a constructor function. Then we exported the class using module.

How do I export multiple classes?

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

Can we export class in NodeJS?

Export class with static method: If you want to export a class with a static method from NodeJS module then the idea is as simple as exporting a class itself.

How do I export multiple Const?

Use named exports to export multiple variables in TypeScript, e.g. export const A = 'a' and export const B = 'b' . The exported variables can be imported by using a named import as import {A, B} from './another-file' . You can have as many named exports as necessary in a single file.


1 Answers

You will need to assign to module.exports, not the local exports variable.

like image 173
Bergi Avatar answered Sep 19 '22 16:09

Bergi