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

posted on 2021-01-18 17:19  KyleLjc  阅读(309)  评论(0编辑  收藏  举报

导航