webpack-dev-middleware webpack-hot-middleware

概述


webpack-dev-middleware与webpack-hot-middleware用于本地开发
[webpack-dev-middleware](http://webpack.github.io/docs/webpa ck-dev-middleware.html)为一个内建express服务器
webpack-hot-middleware为一中间层插件,用于热加载更新网页,需基于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实现

var express = require('express')
var app = express();
app.use(devMiddleware);

文件结构发生变化时会触发重编译(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事件触发,类型为reload时触发页面刷新
  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()
]

例子


你可能感兴趣的:(webpack-dev-middleware webpack-hot-middleware)