Nodejs SyntaxError: Unexpected token import

FEvivi 2017-05-19

报错信息:

server.js:1
(function (exports, require, module, __filename, __dirname) { import Koa from 'koa';
                                                              ^^^^^^
SyntaxError: Unexpected token import
    at createScript (vm.js:53:10)
    at Object.runInThisContext (vm.js:95:10)
    at Module._compile (module.js:543:28)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
    at Module.runMain (module.js:605:10)
    at run (bootstrap_node.js:423:7)
    at startup (bootstrap_node.js:147:9)

报错原因:

。可能为安装babel,或安装错误,尝试重装

   npm i -D babel-cli babel-polyfill babel-preset-es2015 babel-preset-stage-2

。无法直接运行babel-node命令

   在package.json里面添加运行名:

    

"scripts": {
    "server": "node api/src/server.js --exec babel-node --presets es2015,stage-2",

    "server2": "nodemon api/src/server.js --exec babel-node --presets es2015,stage-2"
}

也可以在根目录创建文件:.babelrc

写入:

{
  "presets": ["es2015", "stage-2"],
  "plugins": []
}

server可以缩写:"server": "node api/src/server.js --exec babel-node

or just write like this simple:

{
  "dependencies": {
    "babel-cli": "^6.0.0",
    "babel-preset-es2015": "^6.0.0"
  },
  "scripts": {
    "start": "babel-node --presets es2015 app.js"
  }
}

$ npm start


更多实例应用扫码体验:

Nodejs SyntaxError: Unexpected token import

相关推荐