Skip to content Skip to sidebar Skip to footer

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';

Solution 1:

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

File class.js:

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

File code.js:

varMyClass = require('./class.js');
var myclass = newMyClass();
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:MyClassisnot a constructor 

Also to people suggesting that this should be used:

exportdefault 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.

Post a Comment for "How Can I Export A Class In Node?"