Open iliuyt opened 6 years ago
网上有很多express+webpack的热更新,但是koa2的很少,这两天研究了一下子,写一个简单的教程。
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"] }
plugins: [ new webpack.HotModuleReplacementPlugin() ]
// 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;
// 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;
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,现在可以运行了
请问在本地开发模式中,你的模板中如何插入webpack打包后的js和css,也就是怎么获取webpack打包后的js和css的路径
网上有很多express+webpack的热更新,但是koa2的很少,这两天研究了一下子,写一个简单的教程。
1、需要的包
2、webpack.config配置
3. koa2支持的中间件webpack-dev-middleware的实现
4. koa2支持的中间件webpack-hot-middleware的实现
5. koa2实现添加中间件
ok,现在可以运行了