iliuyt / blog

1 stars 0 forks source link

koa2 + webpack 热更新 #12

Open iliuyt opened 6 years ago

iliuyt commented 6 years ago

网上有很多express+webpack的热更新,但是koa2的很少,这两天研究了一下子,写一个简单的教程。

1、需要的包

  1. webpack:用于构建项目
  2. webpack-dev-middleware:用于处理静态文件
  3. webpack-hot-middleware:用于实现无刷新更新

2、webpack.config配置

  1. entry配置webpack-hot-middleware脚本
    entry: {
    app:["webpack-hot-middleware/client?noInfo=true&reload=true","./src/module1.js","./src/module2.js"],
    app2:["webpack-hot-middleware/client?noInfo=true&reload=true","./src/module2.js","./src/module3.js"]
    }
  2. plugins配置HotModuleReplacementPlugin插件用于热更新
plugins: [
        new webpack.HotModuleReplacementPlugin()
    ]

3. koa2支持的中间件webpack-dev-middleware的实现

// devMiddleware.js

const webpackDev  = require('webpack-dev-middleware')

const devMiddleware = (compiler, opts) => {
    const middleware = webpackDev(compiler, opts)
    return async (ctx, next) => {
        await middleware(ctx.req, {
            end: (content) => {
                ctx.body = content
            },
            setHeader: (name, value) => {
                ctx.set(name, value)
            }
        }, next)
    }
}

module.exports=devMiddleware;

4. koa2支持的中间件webpack-hot-middleware的实现

// hotMiddleware.js

const webpackHot = require('webpack-hot-middleware')
const PassThrough = require('stream').PassThrough;

const hotMiddleware = (compiler, opts) => {
    const middleware = webpackHot(compiler, opts);
    return async (ctx, next) => {
        let stream = new PassThrough()
        ctx.body = stream
        await middleware(ctx.req, {
            write: stream.write.bind(stream),
            writeHead: (status, headers) => {
                ctx.status = status
                ctx.set(headers)
            }
        }, next)
    }

}

module.exports = hotMiddleware;

5. koa2实现添加中间件

const Koa = require('koa');
const app = new Koa();
const serve = require('koa-static');

const webpack = require("webpack");
const webpackConfig = require("./webpack.config");
const devMiddleware = require("./devMiddleware");
const hotMiddleware = require('./hotMiddleware');

const compiler = webpack(webpackConfig);

app.use(devMiddleware(compiler));
app.use(hotMiddleware(compiler));

app.use(serve(__dirname + "/dist/", {extensions: ['html']}));

app.listen(3000, () => {
    console.log('app listen at 3000')
});

ok,现在可以运行了

qianlongo commented 5 years ago

请问在本地开发模式中,你的模板中如何插入webpack打包后的js和css,也就是怎么获取webpack打包后的js和css的路径