pig__man pig__man - 2 months ago 5x
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


class bar{
modules.export = bar;

And then in app.js I have

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

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


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.