【问题标题】:Runing a server using import instead of require in NodeJS在 Node JS 中使用 import 而不是 require 运行服务器
【发布时间】:2019-08-25 08:46:41
【问题描述】:

我有以下用于反应应用程序的服务器代码(从创建反应应用程序创建):

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 运行它时,我收到以下错误:

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

SyntaxError: Unexpected token import

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

 "dev": "concurrently \"npm run react\" \"npm run server\"",
 "react": "react-scripts start",
 "server": "node src/server/index.js",

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

【问题讨论】:

    标签: node.js reactjs express


    【解决方案1】:

    您遇到的问题是因为 ESM(导入/导出)在版本 12 中被引入 Node。您有两种选择:如果您使用的是 node v12 或更高版本,您可以关注此link

    如果您使用的是较低版本的节点,则必须使用 babel 来转译您的代码。检查这个link

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-18
      • 1970-01-01
      • 1970-01-01
      • 2019-08-31
      • 2013-09-05
      相关资源
      最近更新 更多