-
Notifications
You must be signed in to change notification settings - Fork 33
/
webpack.server.js
50 lines (41 loc) · 1.21 KB
/
webpack.server.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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import webpack from 'webpack'
import webpackDevMiddleware from 'webpack-dev-middleware'
import webpackHotMiddleware from 'webpack-hot-middleware'
import config from './webpack.config'
export const compiler = webpack(config)
// Based on: https://github.com/dayAlone/koa-webpack-hot-middleware/blob/master/index.js
function applyExpressMiddleware(fn, req, res) {
const originalEnd = res.end
return new Promise(resolve => {
res.end = function (...args) {
originalEnd.apply(this, args)
resolve(false)
}
fn(req, res, () => {
resolve(true)
})
})
}
const devMiddleware = webpackDevMiddleware(compiler, {
noInfo: true,
publicPath: config.output.publicPath
})
export default app => {
app.use(async (ctx, next) => {
/* eslint prefer-const: 0 */
let hasNext = await applyExpressMiddleware(devMiddleware, ctx.req, {
end(content) {
ctx.body = content
},
setHeader(...args) {
ctx.set(...args)
}
})
if (hasNext) { await next() }
})
app.use(async (ctx, next) => {
/* eslint prefer-const: 0 */
let hasNext = await applyExpressMiddleware(webpackHotMiddleware(compiler), ctx.req, ctx.res)
if (hasNext) { await next() }
})
}