webpack4.0 (two) - hot update

webpack4.0 --- hot update                        
   Use webpack can help our development and packaged in the development process, sometimes we only want to amend the section of code and without having to refresh the entire page to see the effect of the change, this time webpack-dev-server (WDS) hot update it can come in handy.
 
1, about WDS hot update, the following points:
     (1) WDS does not refresh the entire page.
  (2) WDS does not output file in memory (no disk IO, faster).
  (3) use HotModuleReplacementPlugin plug (webpack own).
 
2, installation
npm i webpack-dev-server -D

package.json file

3, the project file directory structure

In web10 build a project in the build folder in which to build a webpack.conf.js file

 

4, webpack.conf.js configuration

 1 //声明变量
 2 var webpack = require('webpack');
 3 var PATH = require('path');//这是nodejs的核心模块之一
 4 var SRC_PATH = PATH.resolve(__dirname,'../src');
5 var DIST_PATH = PATH.resolve(__dirname,'../dist');
6 7 8 module.exports = { 9 entry:SRC_PATH+'\\index.js', 10 output:{ 11 path:DIST_PATH, 12 filename:'bundle.js' 13 }, 14 //loader 15 module:{ 16 }, 17 //插件 18 plugins:[ 19 ], 20 devServer:{//开发服务器 21 hot:true,//热更新 22 inline: true,// 23 open:true,//是否自动打开默认浏览器 24 contentBase:DIST_PATH,//发布目录 25 port:'0996',//控制端口 26 host:'0.0.0.0',//host地址 27 historyApiFallback:true, 28 useLocalIp:true,//是否用自己的IP 29 proxy:{ 30 '/action':'http://127.0.0.1:8080/' 31 } 32 } 33 }

 

 

 

 

编译:命令 webpack --config build/webpack.conf.js --mode development

编译后dist里面会多出一个bundle.js   改写一下index.html引入bundle.js

同时npm 允许在package.json文件里面,使用scripts字段自定义脚本命令。

"dev": "webpack-dev-server --mode development --inline --progress --config build/webpack.conf.js"

运行:自动打开浏览器

1 npm run dev

 

访问你写的index.html

 

热更新表现在哪里?

   修改src里的index.js文件 点击保存  同时热更新起效 修改bundle.js里的值,从而起到热更新的效果。

 

 

 

 

 

 缺点                              

  会发现这样虽然解决了网页刷新麻烦的问题 ,但是也有不方便的之处 就是你的dist中的index.html文件要自己手动建 而且打包后的main.js也要自己手动写入,比较麻烦下一篇随笔要讲的一个插件就是可以动态生成html文件,不用手写代码。打包就直接引用。

Guess you like

Origin www.cnblogs.com/xym0996/p/12013656.html