如何导入expressjs

时间:2017-11-28 22:01:10

标签: node.js reactjs express

当我尝试在server.js中导入如下所示:

import SalaryService from '/components/utils/SalaryService';

然后想要像这样使用它:

const salaryService = new SalaryService();
res.send(salaryService.getSalaries('test'));

但是,当我尝试启动我的开发服务器时,我收到以下错误消息:

C:\projects\project\server.js:10
    import SalaryService from '/components/utils/SalaryService';
    ^^^^^^
    SyntaxError: Unexpected token import

我怎么能实现这个目标?

1 个答案:

答案 0 :(得分:1)

取决于&/39; / components / utils / SalaryService'中的module.exports。被安排了。如果它是具有许多函数(或嵌套对象)的对象,则意味着文件SalaryService.js导出一个包含名为' SalaryService'你可以像这样使用解构:

const { SalaryService } = require('/components/utils/SalaryService');

这很好,因为您可以干净地从大对象中选择一些属性:

const { SalaryService, SomeOtherProp } = require('/components/utils/SalaryService');

否则,如果为module.exports直接分配了您想要的函数或对象:

const SalaryService = require('/components/utils/SalaryService');