webpack-middleware.js
1.3 KB
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
'use strict';
const expressMiddleware = require('webpack-dev-middleware')
const webpackHotMiddleware = require('webpack-hot-middleware')
function middleware(doIt, req, res) {
const originalEnd = res.end
return function (done) {
res.end = function () {
originalEnd.apply(this, arguments);
done(null, 0)
}
doIt(req, res, function () {
done(null, 1)
})
}
}
module.exports = function (compiler, option, callbacks) {
const doIt = expressMiddleware(compiler, option);
var action = webpackHotMiddleware(compiler, option.hotConfig);
for (const key in callbacks) {
const exist = doIt[key] && typeof doIt[key] === 'function'
exist && doIt[key].call(doIt, callbacks[key])
}
return function* (next) {
const ctx = this
const req = this.req
const res = this.res
const runNext = yield middleware(doIt, req, {
end: function (content) {
ctx.body = content
},
setHeader: function () {
ctx.set.apply(ctx, arguments)
},
});
const nextStep = yield middleware(action, req, res);
if (runNext && nextStep && next) {
yield* next
}
}
}