koa2裏面使用ES7的語法,如async、await因此須要運行在node7.6以後;但在node7.6以前也能夠利用babel是的koa2能夠運行。
首先項目中安裝babel,和babel的幾個模塊:
npm install babel babel-register babel-preset-env --savejavascript
而後在入口文件中引入‘babel-register’模塊
require('babel-register');
然後引入業務代碼:
require('./server.js');
java
在配置.babelrc文件:node
{ "presets": [ ["env", { "targets": { "node": true } }] ] }
示例:
app.js:npm
require('babel-register'); require('./servers/devserver');
devserver.js:babel
var koa = require('koa'); var app = new koa(); const request = require('request'); let port = process.env.PORT || 8080; console.log("set port:" + process.env.PORT + "; ip:" + process.env.IP); app.use(async (ctx) => { console.log(ctx.url); if (ctx.url.indexOf('/aaa') > -1) { ctx.response.set('content-type', 'text/javascript'); ctx.body = request.get('http://127.0.0.1/aa.bundle.js', function(err, response, body) { console.log(body); }); } }); app.listen(port);