0

In my node project, I have the following code.

import jwt from 'jsonwebtoken';
import config from 'config';

class UserService {
   generateAuthToken(user) {
      const token = jwt.sign({ _id: user._id, isAdmin: user.isAdmin }, config.get('jwtPrivateKey'));
      return token;
   }
}

export new UserService();

This gives me unexpected token error. But if I set it as follows it works.

 export default new UserService();

What is the reason behind this?

1

1 Answer 1

2

export new UserService(); throws an Error because when using named exports, export expects an identifier and new UserService() does not resolve to a valid identifier.

Try this:

export const userService = new UserService();

/** imported like this: */
import { userService } from '../../the-path'

So, the name of identifier MUST be the same when you import a named export.
If you change the export identifier name, you must change that in import as well:

export const service = new UserService(); // <- just service

/** imported like this: */
import { service } from '../../the-path' // <- userService would be undefined. you have to import service

Unlike named exports, default does not have restrictions on the name while importing.

For example:

export default new UserService();

/** while importing, */
import userService from '../../the-path'; // <- works!
import serviceOfUser from '../../the-path'; // <- Works!

Read more about export here

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.