0

I want to export a class with static methods in a module, along with other functions. I'm trying to do

module.exports = { fun: function(){}, class: MyClass } class MyClass { static get prop() { return 'property'; } } 

But it does not work. Is there a way to export class as part of module.exports object?

5
  • I'm using not class but say abc and it's not working -- the error is that abc is not defined when I try to require it from other file. I can do module.exports.abc = MyClass, but that would not allow me to use just MyClass inside the module Commented Mar 2, 2016 at 10:19
  • I see myClass and not MyClass in your exports definition Commented Mar 2, 2016 at 10:20
  • Why don't you use ES6 module exports? export class MyClass {} export function fun() {} Commented Mar 2, 2016 at 10:42
  • @Bergi: ES6 module imports can only be on the top of the file. Sometimes it's necessary to conditional import a module. This is not possible then. Commented Jul 8, 2017 at 17:11
  • @andreas It will be possible with import() statements, and until then you can still just require the transpiled module Commented Jul 8, 2017 at 18:25

1 Answer 1

5

Class definitions aren't hoisted, which means that your class won't be in scope when you declare those exports. Move them down to below the definition.

class MyClass { static get prop() { return 'property'; } } module.exports = { fun: function(){}, class: myClass } 

You'll also need to fix the case on the variable you export.

module.exports = { fun: function(){}, class: MyClass } 

Depending on your Javascript environment, there may be compile time errors if you try and used the reserved word class as a literal object property. You can wrap it in a string to avoid this.

module.exports = { fun: function(){}, "class": MyClass } 
Sign up to request clarification or add additional context in comments.

1 Comment

great, the problem was with hoisting, otherwise it was just an example code for stackoverflow. thank you sir

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.