16
votes

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.

1
Try logging what you get after requiring the module. If it isn't a constructor, what is it?sdgluck
"this is not a problem with exports vs module.exports" Yes it is! exports = MyClass; doesn't export anything. It's a noop. module.exports = ...; is the way to export a single value from a module. The duplicate explains why exports = ...; doesn't work.Felix Kling
You should mark @Bergi answer as correct (by click on gray 'ceck' button on left side of his answer)Kamil Kiełczewski

1 Answers

33
votes

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