使用导入而不是NodeJS中的require运行服务器

时间:2019-08-25 00:13:55

标签: node.js reactjs express

我有一个用于React应用程序的服务器代码(从create react app创建):

$ awk -F: 'FNR==NR {a[$1]++; next} !a[$1]' file2 file1
apple:tasty
apple:red
kiwi:awesome
kiwi:expensive
grape:green

其他服务器端文件也使用“导入”。

尝试通过import config from './../config/config' import app from './express' import mongoose from 'mongoose' // Connection URL mongoose.Promise = global.Promise mongoose.connect(config.mongoUri) mongoose.connection.on('error', () => { throw new Error(`unable to connect to database: ${mongoUri}`) }) app.listen(config.port, (err) => { if (err) { console.log(err) } console.info('Server started on port %s.', config.port) }) 运行它时,出现以下错误:

node server.js

我应该如何启动我的react应用程序,以便客户端可以运行,也可以从一开始运行该server.js服务器?我通常在package.json中使用以下内容:

(function (exports, require, module, __filename, __dirname) { import config from
 './../config/config'
                                                              ^^^^^^

SyntaxError: Unexpected token import

但是在这种情况下,node命令将不起作用。我尝试了一下但没有成功: Using Import In NodeJS server

1 个答案:

答案 0 :(得分:0)

您遇到的问题是因为ESM(导入/导出)是在版本12中引入到Node的。您有两个选择:如果您使用的是节点v12或更高版本,则可以遵循此link

如果使用较低版本的节点,则必须使用babel来转换代码。选中此link