1

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!

5 Answers 5

2

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!

Sign up to request clarification or add additional context in comments.

Comments

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(); 

1 Comment

Thank you very much! This is a perfect explanation to my question!
0

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

Comments

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.

Comments

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() 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.