Koa2取代webpack-dev-server作为开发环境服务器

安装相关依赖
yarn add koa koa-static koa-convert koa-webpack-middleware -D
  • koa-convert: 由于koa2中使用async await异步中间件,而koa-webpack-middleware仍然是generator函数,需要用koa-convert转换下
sever.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
const Koa = require('koa')
const webpack = require('webpack')
const serve = require('koa-static')
const convert = require('koa-convert')
const koaWebpackMiddleware = require('koa-webpack-middleware')
const webpackDevMiddleware = koaWebpackMiddleware.devMiddleware
const webpackHotMiddleware = koaWebpackMiddleware.hotMiddleware

const app = new Koa()
const config = require('./webpack.config')
const compiler = webpack(config)

const wdm = webpackDevMiddleware(compiler, {
watchOptions: {
aggregateTimeout: 300,
poll: true
},
reload: true,
publicPath: config.output.publicPath,
stats: {
colors: true
}
})
app.use(convert(wdm))

app.use(convert(webpackHotMiddleware(compiler)))

app.use(serve(config.output.publicPath))

const server = app.listen(3000, 'localhost', function (err) {
if (err) {
console.error(err)
return
}
console.log('Example app listening on port 3000!\n');
});