我在node.js(ES6)中编写了一个代码,下面是我运行代码所遵循的步骤的问题:
-Step1: ES6代码==>(babel)==>运行时成功编译代码(npm run build)
-Step2: run命令(npm start)抛出错误“SyntaxError:Unexpected token import”
但如果我运行“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"
},
"devDependencies": {
"babel-cli": "^6.22.2",
"babel-core": "^6.22.1",
"babel-preset-es2015": "^6.24.1",
"babel-preset-es2015-node": "^6.1.1",
"babel-preset-es2016-node4": "^6.0.1",
"babel-preset-es2017": "^6.22.0",
"chai": "^3.5.0",
"chai-as-promised": "^6.0.0",
"husky": "^0.13.1",
"mocha": "^3.2.0",
"mocha-duplicate-reporter": "^0.2.1",
"mocha-multi": "^0.9.0",
"mocha-sonar-generic-test-coverage": "0.0.1",
"nock": "^9.0.2",
"node-mocks-http": "^1.6.1",
"nodemon": "^1.11.0",
"nyc": "^10.1.2",
"pact": "^1.0.0",
"rimraf": "^2.5.4",
"sinon": "^1.17.7",
"sinon-chai": "^2.8.0",
"snazzy": "^6.0.0",
"standard": "^8.6.0",
"unit.js": "^2.0.0"
},
.babelrc-
{
"presets": [
"es2016-node4",
"es2017",
"es2015"
]
}
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语句的第一行抛出错误):
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)
});
}
}
}
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",
}
答案 0 :(得分:1)
亲爱的所有问题现在已解决,错误位于以下行server.js中定义的路径中:
- 来自'../ src /api/controllers/accounts.js'的进口帐户
babel或transiled代码没有问题,它由于错误的路径定义告诉代码从src文件夹中选择文件accounts.js而不是来自dist文件夹中存在的转换代码,因此它失败并抛出意外令牌导入的错误。
现在我已经使用npm run start更正了相对路径及其工作正常。
非常感谢你的支持。
答案 1 :(得分:-1)
要求babel-register模块启动index.js
require('babel-register');
我认为它会解决你的问题。
当您捆绑代码时,您的npm运行构建工作,那时babel根据您提供给webpack / gulp的配置来转换代码。
但是当你启动服务器时,babel并没有将其转换,因为babel并不知道它。