20

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.

sohnryang
  • 725
  • 2
  • 13
  • 27
kubal5003
  • 7,186
  • 8
  • 52
  • 90
  • 1
    Try logging what you get after requiring the module. _If it isn't a constructor, what is it?_ – sdgluck May 23 '16 at 15:38
  • 1
    *"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 May 23 '16 at 21:03
  • You should mark @Bergi answer as correct (by click on gray 'ceck' button on left side of his answer) – Kamil Kiełczewski Dec 29 '16 at 21:27

1 Answers1

37

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

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • 2
    @kubal5003: From that very article: "*`require` returns an object, which references the value of `module.exports` for a given file*". How is my answer wrong? Have you tried using `module.exports = MyClass`? – Bergi May 23 '16 at 19:14
  • 2
    @kubal5003: This answer is correct. If you don't believe that then you need to spend more time learning about Node/CommonJS modules. – Felix Kling May 23 '16 at 21:05
  • This worked for me. This should be accepted as solution. – Sarath Kumar Jan 10 '18 at 06:06