【问题标题】:SyntaxError: Unexpected token import - ExpressSyntaxError:意外的令牌导入 - Express
【发布时间】:2018-09-24 01:40:11
【问题描述】:

我的 index.js 中有这个

import express from 'express'
import data from './data/data'


const app = express();
const PORT = 3000; 

app.listen(PORT, () =>
    console.log(`Your server is running on ${PORT}`)
);

这是我的 package.json

{
    "name": "express-app",
    "version": "1.0.0",
    "description": "backend provisioning",
    "main": "app.js",
    "scripts": {
        "start": "nodemon ./index.js --exec babel-node -e js"
    },
    "author": "B",
    "license": "ISC",
    "devDependencies": {
        "babel-cli": "^6.26.0",
        "babel-preset-env": "^1.6.1",
        "babel-preset-stage-0": "^6.24.1"
    },
    "dependencies": {
        "express": "^4.16.3"
    }
}

当我运行 nodemon 时,我得到了

[nodemon] 1.17.3
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: *.*
[nodemon] starting `node index.js`
/Users/b/Desktop/express-app/index.js:1
(function (exports, require, module, __filename, __dirname) { import express from 'express'
                                                            ^^^^^^

SyntaxError: Unexpected token import
    at createScript (vm.js:80:10)
    at Object.runInThisContext (vm.js:139:10)
    at Module._compile (module.js:607:28)
    at Object.Module._extensions..js (module.js:654:10)
    at Module.load (module.js:556:32)
    at tryModuleLoad (module.js:499:12)
    at Function.Module._load (module.js:491:3)
    at Function.Module.runMain (module.js:684:10)
    at startup (bootstrap_node.js:187:16)
    at bootstrap_node.js:608:3
[nodemon] app crashed - waiting for file changes before starting...

我是否忘记执行任何操作才能使用导入命令?

我这样做了:

npm install --save-dev babel-cli babel-preset-env babel-preset-stage-0
npm install express
nodemon

同样的结果

我也试试这个

rm -rf node_modules/
npm install
nodemon

同样的结果


.babelrc

{
    "presets":[
        "env",
        "stage-0"
    ]
}

【问题讨论】:

  • 我想你也需要安装 babel-core。
  • 你需要运行npm start,而不是nodemon。请注意,您在 start 脚本中向 nodemon 传递了额外的参数
  • 前几天我遇到了同样的问题。我尝试在我的 express 服务器中使用 import 并运行 nodemon 来查看文件,即使我安装了所有必要的依赖项、core、env、stage-0 等...... nodemon 不支持导入吗??
  • @Iso,你是对的!!

标签: node.js express ecmascript-6


【解决方案1】:

最好用

const express = require('express');

而不是

import express from 'express';

【讨论】:

    【解决方案2】:

    如果您的节点版本较低,则会发生这种情况。请至少升级到 v10.0

    【讨论】:

      【解决方案3】:

      使用 require 而不是 import。这可能会有所帮助 例如 : 写这个:

      const express =  require('express')
      

      代替:

      import express from 'express'
      

      【讨论】:

        【解决方案4】:

        我只想概述一下谁遇到这种情况,因为它非常痛苦。 首先,在 ES6 中,不支持同时使用 import Expressrequire express,尽管如此,我们可以使用 esmdynamic 来实现它-babel

        什么是原因,詹姆斯在这里解释Update on ES6

        以及原因Node.js, TC-39, and Modules

        在我的情况下,我在同一个项目中使用了 import 和 require,而且我还需要调试和热重载功能,我遇到了这个错误并想出了一个方法。 首先我决定在我的 package.json 中使用 nodemon 来调试和热重载 如下:

        "debug-api": "nodemon --inspect -r esm src/api/server/index.js",
        "debug-store": "nodemon --inspect -r esm dist/store/server/index.js",
        "debug": "concurrently npm:debug-*" // if you add --source-maps to here it will make HMR
        

        我已经删除了 .babelrc 文件,并且我只在 webpack 的一个地方定义了加载器,如下所示

                    use: {
                        loader: 'babel-loader',
                        options: {
                            presets: ["@babel/react", ["@babel/preset-env", {
                                "useBuiltIns": "usage",
                                "shippedProposals": true,
                                "debug": true,
                                "include": ["es7.promise.finally", "es7.symbol.async-iterator", "es6.array.sort"],
                                "modules": false,     
                              }]
                            ],
                            plugins: [
                                ["@babel/plugin-transform-regenerator", {
                                    "asyncGenerators": true,
                                    "generators": true,
                                    "async": true
                                  }],
                                    [
                                        "@babel/plugin-transform-runtime",
                                        {
                                          "corejs": false,
                                          "helpers": true,
                                          "regenerator": true,
                                          "useESModules": true
                                        }
                                      ],
                                      "@babel/plugin-proposal-class-properties",
                                      "@babel/plugin-syntax-dynamic-import",
                                      "@babel/plugin-syntax-object-rest-spread",
                                      "react-hot-loader/babel"]
                        }
                    }
                },
        

        并且我可以从 vscode 调试控制台获取进程,launch.json 如下所示

            {
              "type": "node",
              "request": "attach",
              "name": "Node: Nodemon",
              "processId": "${command:PickProcess}",
              "restart": true,
              "protocol": "inspector",
          },
        

        现在一直在调试和热重载,如果有忽略的问题或功能请评论

        【讨论】:

          【解决方案5】:

          NodeJS 原生仅支持 import experimentally,并且仅当您的脚本具有 .mjs 扩展名时。

          这就是为什么你的 package.json 中的 start 指的是 babel-node,它在运行之前将 ES6 代码即时转换为经典 JS。但我怀疑该命令是否会起作用,因为您没有将任何预设传递给 babel 来运行脚本。试试这个命令:

          nodemon --exec babel-node --presets env index.js

          [或]

          将文件重命名为 .mjs 扩展名,然后运行:

          nodemon --experimental-modules index.mjs

          【讨论】:

          • 我尝试了你的第一个选项,运行 nodemon 时得到了相同的结果。
          • 我的节点版本是v8.9.4
          • @ihue 我刚刚在我的盒子里尝试了你在 8.9.4 上的确切脚本,它对我有用。您确定您完全按照提供的方式执行了我的命令吗?您是否遇到与您的问题完全相同的错误?
          • 我想npm start 不是nodemon
          • @ihue 好的,那么您更改了 package.json 以使用我的命令?
          猜你喜欢
          • 2019-08-07
          • 2018-11-10
          • 1970-01-01
          • 2018-07-14
          • 1970-01-01
          相关资源
          最近更新 更多