Explain the module hot replacement function of webpack in detail

front end 2021-04-07 21:41:33
explain module hot replacement function


Developing JavaScript Application time , Every time we save code changes , We all need to reload the browser to refresh the user interface .

image Webpack Developer tools like this can be accessed through Surveillance mode To listen for changes to project files . Once a change is detected ,Webpack Will automatically rebuild the application and reload the browser .

But soon , Developers start thinking , Is there a way to save and update page changes without reloading the browser ? After all , Reloading means that it will be lost in UI The state of any execution on :

  • All modal boxes or dialog boxes we're using will disappear . We need to start from scratch , Repeat step , To make them appear again .
  • The state of our application will be reset . If we use React or Vue A library like that , We need to redo the state change , Or persistent state through local storage .
  • Want to persist state to local storage , We need to write some extra code . Unless we also have this demand in the production environment , Otherwise, you need to add and delete code for debugging every time you develop , It's very inconvenient .
  • Even if we're only interested in CSS The code has made small changes , It also triggers a browser refresh .

and Module hot swap (Hot Module Replacement,HMR) Function is to solve this problem , And now it has become a powerful assistant to speed up front-end development .

HMR How functions work ?

HMR Let's exchange the data while the application is running 、 Add or remove JavaScript modular , Without reloading the browser . stay Webpack It's through Webpack Development server (webpack-dev-server) Create a HMR The server Realized , And the server will go through Websocket With the HMR Runtime communicate .

 sketch HMR The way we work

The process of switching module is as follows :

  • When you first build an application ,Webpack A list file will be generated , Contains the compiled hash and a list of all modules .Webpack Will HMR Runtime Injected into the generated bundle.js In file .
  • Webpack Changes to the file are detected when the file is saved .
  • Webpack The compiler will use the changes we make to build our application , Create a new manifest file and compare it with the old one . This process is also called “ Hot update ”.
  • Hot update The data will be sent to HMR The server , The latter will send updates to HMR Runtime .
  • HMR Runtime Will be unpacked Hot update data , And use the appropriate loader to handle the changes . If we had CSS change , Will call css-loader or style-loader. If we're right JavaScript The code has changed , You will usually call babel-loader.

By enabling HMR function , We don't need to refresh the browser to let the browser download new packages and unpack the application changes .HMR The runtime will accept data from HMR Incoming requests from the server , Contains manifest files and code blocks , Replace the current file in the browser .

At run time HMR When saving code changes , We can actually “Network” On the tab, you can see from HMR Hot update file sent by server :

 Hot update files under the network tab

When “ Hot update ” When the code in the browser cannot be replaced ,HMR The runtime will notify webpack-dev-server. then ,webpack-dev-server The browser will be refreshed to download the new bundle.js file . We can pass in Webpack Add in configuration hotOnly:true To disable this behavior .

How to enable HMR function

In order to enable HMR, We need to let our application know how to deal with Hot update . We can instantiate it Webpack Open module.hot API To achieve :

First , We need to Webpack Add... To the configuration file hot: true To enable HMR, As shown below :

// webpack.config.js
module.exports = {
entry: {
app: './src/index.js',
},
devtool: 'inline-source-map',
devServer: {
hot: true,
// ... Ignore other configurations 
},
plugins: [
// Open this plug-in 
new webpack.HotModuleReplacementPlugin(),
],
}
 Copy code 

after , We have to use module.hot API Handle incoming HMR request . This is an ordinary one JS Examples of project implementation :

// index.js
import component from "./component";
document.body.appendChild(component);
// Check for support HMR Interface 
if (module.hot) {
// Support hot update 
module.hot.accept();
}
 Copy code 

Once you tell Webpack We support HMR,HMR The runtime and loader take over the processing of the update .

however , Implement... For complex applications HMR It can be tricky , Because we may have undesirable side effects , for example Event handlers that are still bound to old functions , Especially when you use React or Vue A library like that . Besides , We also need to make sure that Enabled only in development HMR.

But before we try to do it ourselves HMR Before , It is suggested that you first find out the available solutions for our project , because HMR Has been integrated into many popular JavaScript In the application builder .

Create React App and Next.js It's all built in React Fast Refresh,React Specific hot overload implementations . and Vue CLI 3 Of HMR It is through vue-loader Realized .Svelte and Angular They have their own HMR Integrate , So there's no need to write integration from scratch .

Summary

Hot module replacement allows us to view the effect of code changes in the browser without refreshing the browser , So you can keep the state of the front-end application .

But realize HMR It can be tricky , Because it has some side effects . Fortunately, ,HMR Has been in many JavaScript In the application generator . So we can enjoy this function directly , You don't have to do it yourself .

If there are errors in the translation or other areas that need to be improved , Welcome to Nuggets translation plan Revise the translation and PR, You can also get bonus points . At the beginning of the article Permanent link to this article That's what this article is about GitHub Upper MarkDown link .


Nuggets translation plan It is a community that translates high-quality Internet technology articles , The source of the article is Nuggets Share articles in English on . Content coverage AndroidiOS front end Back end Blockchain product Design Artificial intelligence Other fields , If you want to see more excellent translations, please keep your eyes on Nuggets translation plan Official micro-blog Know about columns .

版权声明
本文为[front end]所创,转载请带上原文链接,感谢
https://qdmana.com/2021/04/20210407213622972S.html

  1. Behind the miracle of the sixth championship is the football with AI blessing in the Bundesliga
  2. An easy to use Visual Studio code extension - live server, suitable for front-end gadget development
  3. 用 Python 抓取公号文章保存成 HTML
  4. User login of front end spa project based on Vue and Quasar (2)
  5. Summary of common selectors in CSS
  6. Using Python to grab articles with public number and save them as HTML
  7. To "restless" you
  8. 【免费开源】基于Vue和Quasar的crudapi前端SPA项目实战—环境搭建 (一)
  9. 【微信小程序】引入阿里巴巴图标库iconfont
  10. layui表格点击排序按钮后,表格绑定事件失效解决方法
  11. Unity解析和显示/播放GIF图片,支持http url,支持本地file://,支持暂停、继续播放
  12. 【vue】 export、export default、import的用法和区别
  13. [free and open source] crudapi front end spa project based on Vue and Quasar
  14. [wechat applet] introduces Alibaba icon library iconfont
  15. Layui table click Sort button, table binding event failure solution
  16. Element树形控件Tree踩坑:修改current-node-key无效
  17. Unity parses and displays / plays GIF images, supports HTTP URL, supports local file: / /, supports pause and resume playback
  18. Element树形控件Tree踩坑:修改current-node-key无效
  19. The usage and difference of export, export default and import
  20. Element tree control: invalid to modify current node key
  21. Element tree control: invalid to modify current node key
  22. linux下安装apache(httpd-2.4.3版本)各种坑
  23. How to install Apache (httpd-2.4.3) under Linux
  24. 程序员业余时间写的代码也算公司的?Nginx之父被捕引发争议
  25. Nacos serialize for class [com.alibaba.nacos.common.http.HttpRestResult] failed.
  26. Do programmers write code in their spare time? Controversy over the arrest of nginx's father
  27. Nacos serialize for class [ com.alibaba.nacos . common.http.HttpRestResult ] failed.
  28. Seamless management of API documents using eolink and gitlab
  29. vue 的基础应用(上)
  30. 28岁开始零基础学前端,这些血的教训你一定要避免
  31. Basic application of Vue
  32. Starting at the age of 28, you must avoid these bloody lessons
  33. Ubuntu 16.04 can not connect to the wireless solution and QQ installation
  34. Industry security experts talk about the rapid development of digital economy, how to guarantee the security of data elements?
  35. 利用Vue实现一个简单的购物车功能
  36. Behind the "tireless classroom" and teacher training, can byte education really "work wonders"?
  37. Using Vue to realize a simple shopping cart function
  38. 【css】伪类和伪类元素的区别
  39. 【css效果】实现简单的下拉菜单
  40. 【vue】父子组件传值
  41. The difference between pseudo class and pseudo class elements
  42. [CSS effect] simple drop-down menu
  43. [Vue] value transfer by parent-child component
  44. 【css】设置table表格边框样式
  45. 【css】修改input,textarea中的placeholder样式
  46. vue-router的两种模式(hash和history)及区别
  47. CSS3的滤镜filter属性
  48. [CSS] set table border style
  49. [CSS] modify the placeholder style in input and textarea
  50. Two modes of Vue router (hash and History) and their differences
  51. Filter property of CSS3
  52. 全局安装gulp 报错问题解决
  53. Solution of error report in global installation of gulp
  54. 18个好用的自定义react hook
  55. 你应该知道的常用服务器HTTP状态码?
  56. 18 user defined react hooks
  57. What HTTP status codes should you know about common servers?
  58. 手把手教你打造属于自己团队的前端小报系统
  59. Hand in hand to teach you to build your own front-end tabloid system
  60. In 2021, enterprise SEO actual operation, how to less update, batch ranking regional words?