koa2 + webpack 热更新

网上有很多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"]
}
  1. 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')
});


6 package.json附上,版本不同可能会导致乱七八糟的问题,所以给上能用的版本。

{
  "name": "demo",
  "version": "1.0.0",
  "main": "index.js",
  "repository": "",
  "author": "",
  "license": "MIT",
  "dependencies": {
    "html-webpack-plugin": "^2.29.0",
    "koa": "^2.3.0",
    "koa-static": "^4.0.1",
    "webpack": "^3.3.0",
    "webpack-dev-middleware": "^1.11.0",
    "webpack-hot-middleware": "^2.18.2"
  }
}

ok,现在可以运行了

posted @ 2017-07-21 12:13  Liuyt  阅读(8541)  评论(1编辑  收藏  举报