“熱更新”:對應的是 'webpack-dev-middleware' 中間件
“熱加載”:對應的是 'webpack-hot-middleware' 中間件
為了使用這兩個中間件,必須修改“webpack.config.js"和”server.js“
webpack配置文件(“webpack.config.js")和上一篇博文寫的大致相同,下面給出一個vue+webpack開發常用的配置:
const path = require('path'); const htmlPlugin = require('html-webpack-plugin'); const webpack = require('webpack'); module.exports = { entry: ['webpack-hot-middleware/client','./index.js'], output:{ path: path.resolve(__dirname,'./dist'), filename: '[name].bundle.js' }, plugins:[ new webpack.HotModuleReplacementPlugin(), new webpack.NoEmitOnErrorsPlugin(), new htmlPlugin({ template: path.resolve(__dirname,'./index.html') }) ], resolve:{ extensions: ['.js','.vue'], alias:{ 'vue':'vue/dist/vue.js', '$': path.resolve(__diraname, 'src') } }, module:{ loaders:[ { test: /\.js$/, loader: 'babel-loader?presets=env', include: path.resolve(__dirname,'src') },{ test: /\.vue$/, loader: 'vue-loader', include: path.resolve(__dirname,'src') } ] } }
ps:這里額外說一下alias,這里可以理解為把import xx from 'yyy' 的 ‘yyy’替換掉,例如import App from '@/views/app'變成了import App from 'D://xxx1/xxx2/src/views/app'
值得注意的是entry和plugins的變化:
entry多引入了一個'webpack-hot-middleware/client'入口文件 ,這個很明顯就是一個核心為“window.location.reload();”的js文件,用於刷新瀏覽器,生成的時候會被webpack一並打包進bundle.js
plugins多了兩個:
new webpack.HotModuleReplacementPlugin(), new webpack.NoEmitOnErrorsPlugin()
官方解釋大概是說用來替換一些字解釋,使得錯誤界面不會太亂。
你會發現這兩處改寫都是為了'webpack-hot-middleware'刷新瀏覽中間件而改寫的。
express的寫法(server.js)如下:
const express = require('express'); const webpack = require('webpack'); const config = require('./webpack.config.js'); //給webpack帶上配置 const compiler = webpack(config); //自動更新編譯代碼中間件 const devMiddleWare = require('webpack-dev-middleware')(complier,{}); //自動刷新瀏覽器中間件 const hotMiddleWare = require('webpack-hot-middleware')(compiler); const server = express(); //調用2個中間件 server.use(devMiddleWare); server.use(hotMiddleWare); server.listen(8088);
完事兒~~
這個時候你去試下修改app.vue那些文件,你就會發現編譯的代碼自動刷新了~~
webpack3.6新增了簡易方法