Node.js ES6 how to export class from module?

24,286

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

Share:
24,286
kubal5003
Author by

kubal5003

Software developer specializing in web technologies

Updated on July 09, 2022

Comments

  • kubal5003
    kubal5003 almost 2 years

    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.

  • Bergi
    Bergi almost 8 years
    @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?
  • Felix Kling
    Felix Kling almost 8 years
    @kubal5003: This answer is correct. If you don't believe that then you need to spend more time learning about Node/CommonJS modules.
  • Sarath Kumar
    Sarath Kumar over 6 years
    This worked for me. This should be accepted as solution.