我试图在我的服务器端代码中加入es6。在运行服务器时使用babel-node工作,但是在运行mocha测试时我无法将es6编译为es5代码。
这是我的文件夹结构
我有一个server.js启动一个worker.js文件(有快递服务器)
server.js文件
import {SocketCluster} from 'socketcluster';
const socketCluster = new SocketCluster({
workers:1,
brokers:1,
port: 3000,
appName:null,
workerController: __dirname + '/worker.js',
brokerController: __dirname + '/broker.js',
socketChannelLimit: 1000,
crashWorkerOnError: true
})
worker.js文件
export const run = (worker) => {
console.log(' >> worker PID: ',process.pid);
const app = express();
const httpServer = worker.httpServer;
const scServer = worker.scServer;
app.use(cookieParser())
httpServer.on('request', app);
app.get('/',(req,res) => {
console.log('recieved')
res.send('Hello world')
})
}
手动运行服务器时,它可以使用以下脚本
"start": "nodemon server/server.js --exec babel-node"
然而,当我尝试使用mocha运行测试文件时,我得到一个意外的令牌" export"错误'
(function (exports, require, module, __filename, __dirname) { export const run = (broker) => {
^^^^^^
SyntaxError: Unexpected token export
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:511:25)
at Object.Module._extensions..js (module.js:550:10)
at Module.load (module.js:456:32)
at tryModuleLoad (module.js:415:12)
at Function.Module._load (module.js:407:3)
at Module.require (module.js:466:17)
at require (internal/module.js:20:19)
at initBrokerServer (/home/avernus/Desktop/projects/node-sc-react/node_modules/sc-broker/server.js:178:25)
at process.<anonymous> (/home/avernus/Desktop/projects/node-sc-react/node_modules/sc-broker/server.js:498:9)
这是启动mocha测试的脚本
"test": "mocha test/server/*.js --compilers js:babel-register"
我错过了别的什么吗?
这是测试文件
import server from '../../server/server';
import http from 'http';
import assert from 'assert';
import {expect} from 'chai';
describe('Express server',() =>{
it('should return "Hello World"',() => {
http.get('http://127.0.0.1:3000',(res) => {
expect(res).to.contain('wtf world')
})
})
})
答案 0 :(得分:3)
在将测试脚本传递给mocha运行测试之前,需要使用Babel将测试脚本从ES2015
转换为ES5
。您可以按照以下方式添加/编辑package.json
...
"scripts": {
"test": "mocha --compilers js:babel-core/register --recursive"
},
...
<强>更新强>
Mocha弃用--compiler
标志。有关详细信息,请查看this page。新的npm脚本应如下所示
...
"scripts": {
"test": "mocha --require babel-register --recursive"
},
...
答案 1 :(得分:-1)
原来我需要在server.js文件中指定initController
以确保所有文件都由babel编译。这是我正在使用的websocket框架特有的问题。