Javascript Babel成功地传输了ES6代码(node.js),但什么时候做;“新产品管理启动”;它抛出;SyntaxError:意外的令牌导入“;

Javascript Babel成功地传输了ES6代码(node.js),但什么时候做;“新产品管理启动”;它抛出;SyntaxError:意外的令牌导入“;,javascript,node.js,ecmascript-6,babeljs,ecmascript-5,Javascript,Node.js,Ecmascript 6,Babeljs,Ecmascript 5,我已经在node.js(ES6)中编写了一段代码,下面是我在运行代码时所遵循的步骤的问题: -步骤1: ES6代码==>(babel)==>运行时成功传输代码(npm运行构建) -步骤2: run命令(npm start)抛出错误“SyntaxError:意外令牌导入” 但如果我运行“nodemon./src/index.js--exec babel node”,它会成功运行。 在这里发布这个问题之前,我还试图通过在stackoverflow上搜索类似的问题来理解失败的原因,但无法使我的代码正常

我已经在node.js(ES6)中编写了一段代码,下面是我在运行代码时所遵循的步骤的问题:

-步骤1: ES6代码==>(babel)==>运行时成功传输代码(npm运行构建)

-步骤2: run命令(npm start)抛出错误“SyntaxError:意外令牌导入”

但如果我运行“nodemon./src/index.js--exec babel node”,它会成功运行。 在这里发布这个问题之前,我还试图通过在stackoverflow上搜索类似的问题来理解失败的原因,但无法使我的代码正常工作

我真的很感谢你们的帮助,我不知道如何从这里开始,我们的整个生产部署都因为这个问题而受阻:(

下面是我的代码文件,显示我已经在代码中使用了babel和.babelrc: Package.json-

"dependencies": {
"babel-preset-es2015": "^6.24.1",
"body-parser": "^1.16.0",
"connect-timeout": "^1.8.0",
"core-js": "^2.4.1",
"cors": "^2.8.1",
"express": "^4.14.1",
"joi": "^10.2.2",
"jsonapi-serializer": "^3.5.3",
"mongoose": "^4.10.4",
"mongoose-rename-id": "^1.0.2",
"nedb": "^1.8.0",
"path": "^0.12.7",
"randomstring": "^1.1.5",
"request": "^2.79.0",
"request-promise": "^4.1.1",
"swagger-express-mw": "^0.1.0",
"swagger-ui": "^2.2.10",
"yamljs": "^0.2.8"
},

},

index.js的代码:

'use strict'
import * as path from 'path'
import {PORT} from 'config'

// config module loads the configuration from the folder the process is run
process.env[ 'NODE_CONFIG_DIR' ] = path.resolve(__dirname, '/config')

import server from './server'

// Start the server
server(PORT)
server.js的代码:

import cors from 'cors'
import SwaggerExpress from 'swagger-express-mw'
import bodyParser from 'body-parser'
import timeout from 'connect-timeout'
import * as YAML from 'yamljs'
import * as path from 'path'
import account from '../src/api/controllers/accounts.js'

const version = {
file: YAML.load(path.join(__dirname, 'version.yml'))
}

var config = {
appRoot: __dirname,
swaggerFile: path.resolve(__dirname, 'api', 'swagger', 'swagger.json'),
basePath: '/api/v1',
swaggerSecurityHandlers:{
    basicAuth :async function(req, authOrSecDef, scopesOrApiKey, callback){
      try{
       //let data = true
        console.log(req.headers.authorization)

    let data = await account.authenticate(req.headers.authorization)
    if(data.statusCode==200){
        console.log(data)
        callback(null,true);
      }
      else
      callback(new Error("Access denied"))
      }catch(err){
        callback(new Error("Access denied"))
      }
     console.log("response ...."+data)
    }
}

}

export default function start (serverPort) {
SwaggerExpress.create(config, function (err, swaggerExpress) {
if (err) {
  throw err
}

var app = require('express')()

// Hack to override the host and port
app.get(path.resolve(config.basePath, '/api-docs'), function (req, res) {
  swaggerExpress.runner.swagger.host = req.get('host')
  // Set correct version for the API
  swaggerExpress.runner.swagger.info.version = version.file.build.name
  res.json(swaggerExpress.runner.swagger)
})

// Customize SwaggerUI
var swaggerUIParams = {
  swaggerUi: config.basePath + '/docs',
  apiDocs: config.basePath + '/api-docs'
}

// Add for version
app.get('/version', function (req, res) {
  // Load yaml file using YAML.load

  res.json(version.file.build)
})

// serves the Swagger documents and Swagger UI
app.use(swaggerExpress.runner.swaggerTools.swaggerUi(swaggerUIParams))

app.use(cors())

app.use(bodyParser.json())

app.use(timeout('6s'))

// install middleware
swaggerExpress.register(app)

app.listen(serverPort)
})
}
Accounts.js的代码(这里它实际上在import语句的第一行抛出错误):

package.json中的脚本:

"scripts": {
"build:transpile": "babel src/ -d dist",
"build:copy-resources": "cp -r config dist && cp -r src/api/swagger dist/api 
&& cp src/version.yml dist",
"build": "rimraf dist && npm run build:transpile && npm run build:copy-
 resources",
"devstart": "nodemon ./src/index.js --exec babel-node",
"start": "node dist/index.js",
}

需要babel注册模块启动index.js

require('babel-register');

我想这会解决你的问题

当您绑定代码时,您的npm运行构建工作,此时babel将根据您提供给webpack/gulp的配置传输您的代码


但当您启动服务器时,babel不会传输它,因为babel没有意识到这一点。

亲爱的,所有问题现在都解决了,错误出现在server.js中定义的路径下的下一行:

-从“../src/api/controllers/accounts.js”导入帐户

babel或transpiled代码没有问题,这是因为错误的路径定义告诉代码从src文件夹中选择文件accounts.js,而不是从dist文件夹中存在的transpiled代码中选择文件accounts.js,因此它失败并引发意外令牌导入错误

现在,我已经纠正了相对路径,并且它在npm run start中也可以正常工作


非常感谢您的支持。

显然,npm start运行的脚本试图运行源文件,而不是Babel创建的传输文件。我们无法告诉您原因,您需要查看您的package.json和路径等。@t.J.Crowder Crowder transpilation后的Crowder(Babel src/-d dist)Babel将源代码放在dist文件夹中,然后它将运行“node dist/index.js”,我可以在控制台日志中看到这一点。>>node dist/index.js/Users/bahubali/gautam/YAG/src/api/controllers/accounts.js:3从'request promise'^^^^^^^^语法导入请求错误:createScript处意外的令牌导入(vm.js:56:10)在模块处的Object.runInThisContext(vm.js:97:10)处编译(Module.js:542:28)T.J.Crowder但如果我运行“nodemon./src/index.js--exec babel node”但是,在package.json中使用dev依赖关系并不是一个好主意explicitly@ShubhamSinglaSingla您可以在下面的my package.json“scripts”中找到可用的脚本:{“build:transfile”:“babel src/-d dist”,“build:copy resources”:“cp-r config dist&&cp-r src/api/swagger dist/api&&cp src/version.yml dist”,“build”:“rimraf dist&&npm run build:transfile&&npm run build:copy-resources”,“devstart”:“nodemon./src/index.js--exec babel node”,“start”:“node dist/index.js”,}对于格式混乱表示歉意,如果您需要任何其他信息,请告诉我。我也尝试过此方法,但收到了相同的错误。请解释
babel register
的作用,以及如何修复TO的错误。还请添加参考资料(手册/文档链接)到您答案中的信息。@尝试捕获最终检查以下链接:1.2.我的应用程序出现相同的错误,但我无法跟踪路径,它显示的是服务而不是距离。在我的传输代码中,它显示的是此路径:var cov_kpnmn6y1z=函数(){var path='/Users/jack/application/api/server/app.js',hash='467c6935dad303s84b99396ce4924144ds6fcf4aef18',
import cors from 'cors'
import SwaggerExpress from 'swagger-express-mw'
import bodyParser from 'body-parser'
import timeout from 'connect-timeout'
import * as YAML from 'yamljs'
import * as path from 'path'
import account from '../src/api/controllers/accounts.js'

const version = {
file: YAML.load(path.join(__dirname, 'version.yml'))
}

var config = {
appRoot: __dirname,
swaggerFile: path.resolve(__dirname, 'api', 'swagger', 'swagger.json'),
basePath: '/api/v1',
swaggerSecurityHandlers:{
    basicAuth :async function(req, authOrSecDef, scopesOrApiKey, callback){
      try{
       //let data = true
        console.log(req.headers.authorization)

    let data = await account.authenticate(req.headers.authorization)
    if(data.statusCode==200){
        console.log(data)
        callback(null,true);
      }
      else
      callback(new Error("Access denied"))
      }catch(err){
        callback(new Error("Access denied"))
      }
     console.log("response ...."+data)
    }
}

}

export default function start (serverPort) {
SwaggerExpress.create(config, function (err, swaggerExpress) {
if (err) {
  throw err
}

var app = require('express')()

// Hack to override the host and port
app.get(path.resolve(config.basePath, '/api-docs'), function (req, res) {
  swaggerExpress.runner.swagger.host = req.get('host')
  // Set correct version for the API
  swaggerExpress.runner.swagger.info.version = version.file.build.name
  res.json(swaggerExpress.runner.swagger)
})

// Customize SwaggerUI
var swaggerUIParams = {
  swaggerUi: config.basePath + '/docs',
  apiDocs: config.basePath + '/api-docs'
}

// Add for version
app.get('/version', function (req, res) {
  // Load yaml file using YAML.load

  res.json(version.file.build)
})

// serves the Swagger documents and Swagger UI
app.use(swaggerExpress.runner.swaggerTools.swaggerUi(swaggerUIParams))

app.use(cors())

app.use(bodyParser.json())

app.use(timeout('6s'))

// install middleware
swaggerExpress.register(app)

app.listen(serverPort)
})
}
import request from 'request-promise'

export default account()

function account() { 

return {

authenticate: async function authenticate (authheader) {
console.log("Sending call for Account")
   let temp = (authheader).split(" ")
  console.log(temp[1])
  let buf = new Buffer(temp[1], 'base64'); // create a buffer and tell it the 
data coming in is base64
  let plain_auth = buf.toString();        // read it back out as a string
  console.log("Decoded Authorization ", plain_auth);
  const cred = plain_auth.split(':')


 const options={

    uri: `http://localhost:3000/api/account/${cred[0]}`,
    json: true,
    resolveWithFullResponse: true,
    headers: {
      'Content-Type': 'application/json; charset=utf-8',
      'Accept': 'application/json; charset=utf-8'
     // 'Authorization':authheader
    },
    method: 'GET'

  }

   return request(options).then((response) => {

      console.log(response.statusCode)
      return {
        "statusCode":response.statusCode,
        "body":response.body
              }    

}).catch((err) => {
    console.log(err);
    console.log('errorstatuscode:' + err.statusCode)
});


   }



  }

}
"scripts": {
"build:transpile": "babel src/ -d dist",
"build:copy-resources": "cp -r config dist && cp -r src/api/swagger dist/api 
&& cp src/version.yml dist",
"build": "rimraf dist && npm run build:transpile && npm run build:copy-
 resources",
"devstart": "nodemon ./src/index.js --exec babel-node",
"start": "node dist/index.js",
}