webpack-dev-middleware改造成koa中件间
const webpackDev = require('webpack-dev-middleware'); function applyMiddleware(middleware, req, res) { const _send = res.send; return new Promise((resolve, reject) => { try { res.send = function () { _send.apply(res, arguments) && resolve(false); }; middleware(req, res, resolve.bind(null, true)); } catch (error) { reject(error); } }); } module.exports = ({compiler, others}) => { const middleware = webpackDev(compiler, others); return async (ctx, next) => { const hasNext = await applyMiddleware(middleware, ctx.req, Object.assign(ctx.res, { send: content => {return ctx.body = content} })) if(hasNext){ await next(); } } }
参考: https://segmentfault.com/a/1190000004883199