pig__man pig__man - 3 months ago 12
Javascript Question

Called local class with Node

I'm having a small issue with node and calling a local class in another file from app.js,

For example

foo.js

class bar{
constructor(){
}
}
modules.export = bar;


And then in app.js I have

var foo = require('./foo');
var fooClass = new bar();


But it throws an error saying
bar
is undefined. What am I doing wrong here?

Answer

Use module.exports, not modules.export.

Also check how you're importing. When you use var foo = require('./foo');, you must also use var fooClass = new foo(). The local variable / class will match the name you gave it when you required it, not the name you gave it when you defined it in the original file.

For example, the following would also work:

var Bar = require('./foo');
var bar = new Bar();

You can label your variables whatever you want when you import / require them, regardless of their names when you declare them -- including classes.