webpackHotMiddleware改造成koa支持的中间件

const stream = require('stream');
const webpackHot = require('webpack-hot-middleware');
const PassThrough = stream.PassThrough;
module.exports = ({compiler, others}) => {
    const middleware = webpackHot(compiler, others);
    return async (ctx, next) => {
        const res = Object.assign({}, ctx.res);
        const streamInstance = new PassThrough();
        streamInstance.on('data', chunk => {
            if(chunk && global.cache &&global.cache.updateCache){
                global.cache.updateCache();
            }
        });
        ctx.body = streamInstance;
        await middleware(
            ctx.req,
            Object.assign(res, {
                write: streamInstance.write.bind(streamInstance),
                writeHead: (
                    status ,
                    headers,
                ) => {
                    ctx.status = status;
                    ctx.set(headers);
                },
                end: (content) => {
                    ctx.body = content || 'devMiddleWare no body';
                },
            }),
            next
        )
        
    }
}

 

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

导航