Barodapride Barodapride - 23 days ago 17
Node.js Question

How can I export a class in node?

This seems like a simple thing but I'm a bit of a node/javascript newbie. How can I import a class from another file using node 7.0.0?

I defined my class in one file:

'use strict';

class MyClass {
...
};

module.exports = MyClass;


And I want to use it in another class:

var MyClass = require('./path/to/otherfile');
...
var myclass = new MyClass(some param);


But I'm getting an error from my linter saying

TypeError: Class constructor MyClass cannot be invoked without 'new'

rsp rsp
Answer

This code is correct and works in Node 7.0.0. See this example:

File class.js:

'use strict';
class MyClass {
}
module.exports = MyClass;

File code.js:

var MyClass = require('./class.js');
var myclass = new MyClass();
console.log('OK');

Run:

node code.js

and you'll see:

OK

What is broken is not your code but your linter but you don't specify what linter are you using so it's hard to say anything more.

I don't know why people suggested that you should use module.exports.MyClass = MyClass; instead of module.exports = MyClass; - it would not only not fix the issue but would actually break the code giving you an error of:

TypeError: MyClass is not a constructor 

Also to people suggesting that this should be used:

export default MyClass;

No, it would give an error in Node 7.0.0:

SyntaxError: Unexpected token export

After reading the comments to this question I wonder how many people have actually run the code because as it turns out the code works fine but all the "solutions" in the comments break it.

I made a GitHub project with the original code and suggested solutions tested on Travis with Node versions 4, 5, 6, and 7. You can see it here:

with test results available at:

When I know which linter is causing the problem I'll add it to the project and we'll see what can be done about it.

Comments