“热更新”:对应的是 ‘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‘ } }, module:{ loaders:[ { test: /\.js$/, loader: ‘babel-loader?presets=env‘, include: path.resolve(__dirname,‘src‘) },{ test: /\.vue$/, loader: ‘vue-loader‘, include: path.resolve(__dirname,‘src‘) } ] } }
值得注意的是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那些文件,你就会发现编译的代码自动刷新了~~
原文地址:https://www.cnblogs.com/amiezhang/p/8303794.html
时间: 2024-10-08 23:21:49