0

For a longer time I've asked myself if there's a real difference between these 3 methods of exporting an entire class in Node.js. Is there a "correct" way or any differences within the different kind of methods?

Let's say we have this example class:

class Foo {
    constructor() {
        this.name = 'foobar';
    }

    bar() {
        console.log(this.name);
    }
}

What would be the correct way of exporting this class in a Node.js environment?

module.exports = new Foo();

or

module.exports = new Foo;

or

module.exports = Foo;

Thanks a lot for any answers in advance!

Riya
  • 15
  • 4

5 Answers5

1
module.exports = new Foo();

This would mean you are exporting an instance of the class and not the class itself.

As in, when you require('./Foo'), you get the object and not the class.

Similar case with the

module.exports = new Foo;

Although JSLint would complain if you omit parenthesis.

But,

module.exports = Foo;

would mean you are exporting the class, you'd be able to use it as such:

const Foo = require('./Foo');
const foo = new Foo();
Faizuddin Mohammed
  • 4,118
  • 5
  • 27
  • 51
1

In addition to @Faizuddin Mohammed's answer you can also make es6 exports this way (which i always do):

export class MyClass { ....

this can be imported like this:

import { MyClass } from "...."

or using default exports:

class MyClass {}
export default MyClass

which would be imported this way:

import MyClass from "..."

Greetings and happy new year!

messerbill
  • 5,499
  • 1
  • 27
  • 38
0

module.exports = Foo is the right choice see the reference here

Kashan
  • 348
  • 3
  • 19
0

There isn't a right way to export classes and the method depends on your needs (do you need to export the class itself or an instance of the class).

The most common way is to use (this exports the class itself)

module.exports = Foo;

or in ES6

export default Foo

and importing would be like

const Foo = require('./Foo');
const foo = new Foo();

or in ES6

import Foo from './Foo'
const foo = new Foo()
Rockey
  • 393
  • 4
  • 18
0

There isn't a "correct" way to export a class, since different exports are suitable for different purposes.

Should you need to export instance of an object, use either

module.exports = new Foo();

or

module.exports = new Foo;

these two options are equivalent.

If it's required to export the class itself, so that the module consumer can create instances on his own, then class export

module.exports = Foo;

is the way to go.

antonku
  • 7,377
  • 2
  • 15
  • 21