我正在尝试使用babel运行我的NodeJS程序,该程序包括ES6语法并从Colyseus库导出。但是,当我运行命令时:
babel-node server.js
出现以下错误消息:
export class MyRoom extends colyseus.Room {
^^^^^^
SyntaxError: Unexpected token export
下面是我的package.json文件:
{
"name": "app",
"version": "1.0.0",
"description": "a description",
"main": "server.js",
"scripts": {
"test": "babel-node server.js",
"build": "babel-node server.js"
},
"author": "henryzhu",
"license": "ISC",
"dependencies": {
"actionhero": "^19.1.2",
"colyseus": "^0.9.33",
"easytimer.js": "^2.3.0",
"express": "^4.16.3",
"socket.io": "^2.1.0",
"socketio": "^1.0.0",
"uniqid": "^5.0.3"
},
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-preset-env": "^1.7.0",
"babel-preset-es2015": "^6.24.1"
}
}
下面是我的server.js文件:
var colyseus = require("colyseus");
var http = require("http");
var express = require("express");
var port = process.env.port || 3000;
var app = express();
app.use(express.static("public", { dotfiles: 'allow' }));
var gameServer = new colyseus.Server({
server: http.createServer(app)
});
export class MyRoom extends colyseus.Room {
// When room is initialized
onInit (options) { }
}
gameServer.listen(port);
答案 0 :(得分:0)
babel-node可能期望使用节点样式模块语法:
module.exports = ...
代替es6样式:
export class ...
编辑:
您可以通过指定.babelrc文件来修复它,如下所示:
{
"presets": ["env"]
}
已安装软件包babel-preset-env
答案 1 :(得分:0)
使用以下(.babel.config.js
)添加配置文件:
module.exports = {
presets: [
'@babel/preset-env'
]
};
然后运行:
babel-node --config-file .babel.config.js server.js
答案 2 :(得分:0)
在下面添加一个配置文件 (babel.config.js) 对我有用。另外,顺序很重要。预设应该在所有插件之前。
module.exports = {
presets: [['@babel/preset-env',{targets: {node:
'current',},loose:true,},],],
plugins: [
'@babel/plugin-syntax-dynamic-import',
'@babel/plugin-syntax-import-meta',
[
'@babel/plugin-transform-runtime',
{
useESModules: true,
},
],
],
};