首页 > 解决方案 > 如何导出类的命名实例?

问题描述

在我的节点项目中,我有以下代码。

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

这给了我意外的令牌错误。但是,如果我按如下方式设置它,它就可以工作。

 export default new UserService();

这背后的原因是什么?

标签: javascriptnode.js

解决方案


export new UserService();抛出一个错误,因为在使用命名导出时,export需要一个标识符并且new UserService()不解析为一个有效的标识符。

试试这个:

export const userService = new UserService();

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

import因此,当您进行命名导出时,标识符的名称必须相同。
如果您更改导出标识符名称,您也必须在导入中更改它:

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

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

与命名导出不同,默认在导入时对名称没有限制。

例如:

export default new UserService();

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

阅读更多关于export 这里


推荐阅读