0

I currently develop a project based on node.js with Babel.

I have a userService.js file that is supposed to be a singleton and manage everything I want with the user and also keep the user's state.

Why would I write this module in this way:

class UserService { //methods //properties}
export default new UserService(); //so it is a singleton

and import it this way:

import userService from 'userService';

and not this way:

export function login() {} //other functions etc
export var user={}

and import it like:

import * as userService from 'userService';

is it only a stylistic difference?

I get that for example importing only the login without the logout method doesn't make sense so exporting a class with all the methods sounds good but the other way has the advantage of not having to use "this" keyword all the time.

arisalexis
  • 2,079
  • 2
  • 21
  • 42
  • [This was an antipattern in ES5](http://stackoverflow.com/q/10406552/1048572) and continues to be so in ES6. Don't create singletons using `new` and a constructor. Just `export default { /* methods, properties }` an object literal. – Bergi Sep 22 '15 at 21:33

1 Answers1

2

You might want to group a set of methods into a single file, that don't necessarily want to always be imported together. For instance, a utilities class might list dozens of functions that you would only want to import one at a time, as needed.

Exporting a default, be it a class encapsulation or a single function, makes it clear what the main intention of that module is. You can also combine default and named exports:

// user.js

export default class User {}
export function getUserInfo()


// ... other file ...

import User, {getUserInfo} from 'user.js'

const user = new User();
getUserInfo(user);

Ultimately it depends how you expect/want your module to be used.

duncanhall
  • 11,035
  • 5
  • 54
  • 86