概述
webpack-dev-middleware與webpack-hot-middleware用于本地開發(fā)
[webpack-dev-middleware](http://webpack.github.io/docs/webpa ck-dev-middleware.html)為一個內建express服務器
webpack-hot-middleware為一中間層插件铸题,用于熱加載更新網(wǎng)頁铡恕,需基于webpack-dev-middleware
webpack-dev-middleware
使用
webpack-dev-middleware不會將文件打包到真是硬盤上,而是打包到內存中丢间,通過webpack.config.js獲取到webpack文件探熔,隨后將其打包到內存中
var webpack = require('webpack')
var webpackConfig = require('./webpack.config')
var compiler = webpack(webpackConfig)
var devMiddleware = require('webpack-dev-middleware')(compiler, {
publicPath: webpackConfig.output.publicPath,
// quiet: true, // quite mode won't output compile message in console
})
服務器則采用express實現(xiàn)
var express = require('express')
var app = express();
app.use(devMiddleware);
文件結構發(fā)生變化時會觸發(fā)重編譯(watch-mode下)
compiler.plugin('compilation', function (compilation) {
console.log('compilation');
compilation.plugin('html-webpack-plugin-after-emit', function (data, cb) {
// do sth here, mostly hot-middleware
cb();
});
})
原理
// TODO
參考
webpack-hot-middleware
使用
hotmiddleware基于devmiddleware
在配置文件中需要加上
var hotMiddleware = require('webpack-hot-middleware')(compiler, {
log: false,
heartbeat: 2000
})
app.use(hotMiddleware)
同時,在重新編譯后要通過hotmiddleware推送
// force page reload when html-webpack-plugin template changes
compiler.plugin('compilation', function (compilation) {
console.log('compilation')
compilation.plugin('html-webpack-plugin-after-emit', function (data, cb) {
hotMiddleware.publish({ action: 'reload' })
cb()
})
})
最后烘挫,在webpack.config.js中需要加上兩條
entry中的app加入client
require('eventsource-polyfill');
var hotClient = require('webpack-hot-middleware/client?noInfo=true&reload=true');
hotClient.subscribe(function (event) {
// client端诀艰,通過event事件觸發(fā),類型為reload時觸發(fā)頁面刷新
if (event.action === 'reload') {
window.location.reload();
}
});
plugins加上
plugins: [
// OccurenceOrderPlugin is needed for webpack 1.x only
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin(),
// Use NoErrorsPlugin for webpack 1.x
new webpack.NoEmitOnErrorsPlugin()
]