在使用ES6语法在expressJS中导出类时,我遇到了一个问题。 我的项目是带有Express JS服务器的Vue CLI项目。
要在ES5中转换快速服务器,我在启动它时将使用以下脚本:
nodemon ./server/index.js --exec babel-node --presets @babel/preset-env
在我尝试导出一个类之前,它运行良好。
class ErrorHandler extends Error {
constructor(statusCode, message) {
super(statusCode, message)
this.statusCode = statusCode
this.message = message
}
}
const handleError = (err, res) => {
if (!err.statusCode) err.statusCode = 500 // Sets a generic server error status code if none is part of the error
const { statusCode, message } = err
res.status(statusCode).json({
status: "error",
statusCode,
message
})
}
export{
ErrorHandler,
handleError
}
这段代码将失败,并返回以下错误:
export default function _classCallCheck(instance, Constructor) {
^^^^^^
SyntaxError: Unexpected token export
at Module._compile (internal/modules/cjs/loader.js:723:23)
at Module._compile (C:\Users\Romain\Documents\Developement\projector\node_modules\pirates\lib\index.js:99:24)
at Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Object.newLoader [as .js] (C:\Users\Romain\Documents\Developement\projector\node_modules\pirates\lib\index.js:104:7)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Module.require (internal/modules/cjs/loader.js:692:17)
at require (internal/modules/cjs/helpers.js:25:18)
at Object.<anonymous> (C:\Users\Romain\Documents\Developement\projector\server\helpers\error.js:10:47)
我尝试删除handleError函数,但仍无法正常工作,但是当我尝试删除ErrorHandler类时,一切都很好,因此它必须来自该类。
我是Node js和babel的新手,经过全部研究,我找不到问题所在。
更新这是package.json
{
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"server": "nodemon ./server/index.js --exec babel-node --presets @babel/preset-env"
},
"dependencies": {
"axios": "^0.19.0",
"bulma": "^0.7.5",
"connect-history-api-fallback": "^1.6.0",
"core-js": "^2.6.5",
"express": "^4.17.1",
"express-session": "^1.16.2",
"mongodb": "^3.3.2",
"passport": "^0.4.0",
"passport-local": "^1.0.0",
"vue": "^2.6.10",
"vue-router": "^3.0.3",
"vuex": "^3.0.1"
},
"devDependencies": {
"@babel/node": "^7.5.5",
"@babel/preset-env": "^7.5.5",
"@vue/cli-plugin-babel": "^3.10.0",
"@vue/cli-service": "^3.10.0",
"node-sass": "^4.12.0",
"nodemon": "^1.19.1",
"sass-loader": "^7.2.0",
"vue-template-compiler": "^2.6.10"
}
}
还有babel.config.js:
module.exports = {
presets: [
'@vue/app',
]
}