加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

React技术栈——HotModuleReplacement

发布时间:2020-12-15 03:28:39 所属栏目:百科 来源:网络整理
导读:Hot Module Replacement是webpack下实现热刷新的模块,由于webpack的坑爹文档,看了很久才搞明白这东西怎么用。 Webapck的热刷新用起来很爽,连续写一个下午,一次刷新都不用,体验棒棒哒。 实现热刷新的主要是HOT MODULE REPLACEMENT(HMR)模块 官方文档很

Hot Module Replacement是webpack下实现热刷新的模块,由于webpack的坑爹文档,看了很久才搞明白这东西怎么用。

Webapck的热刷新用起来很爽,连续写一个下午,一次刷新都不用,体验棒棒哒。

实现热刷新的主要是HOT MODULE REPLACEMENT(HMR)模块

官方文档很坑爹,反正我是看的懵懵懂懂的。官方wiki讲的稍微好些,不过原理多一些

How does it works?

<hr/>

Webpacks adds a small HMR runtime to the bundle,during the build process,that runs inside your app. When the build completes,Webpack does not exit but stays active,watching the source files for changes. If Webpack detects a source file change,it rebuilds only the changed module(s). Depending on the settings,Webpack will either send a signal to the HMR runtime,or the HMR runtime will poll webpack for changes. Either way,the changed module is sent to the HMR runtime which then tries to apply the hot update. First it checks whether the updated module can self-accept. If not,it checks those modules that have required the updated module. If these too do not accept the update,it bubbles up another level,to the modules that required the modules that required the changed module. This bubbling-up will continue until either the update is accepted,or the app entry point is reached,in which case the hot update fails.

在构建时,webapck添加一个小的HMR实例到bundle内部,当构建完成后,webpack不再存在但保持监控源文件。如果webpack检测到文件变化,会重新构建被改变的文件。根据设置,webpack要么发送一个信号给HMR实例,要么检查webpack的变化。另外,被改变的模块被发送到HMR runtime,用来做热替换。首先检查,被更新的模块能否self-accept【指是否被HMR跟踪】?

From the app view

The app code asks the HMR runtime to check for updates. The HMR runtime downloads the updates (async) and tells the app code that an update is available. The app code asks the HMR runtime to apply updates. The HMR runtime applies the update (sync). The app code may or may not require user interaction in this process (you decide).

app询问HMR实例是否有更新。如果有更新,HMR实例会异步下载更新代码,并通知app已经准备就绪。app源码请求HMR实例开始更新。HMR实例同步更新。app可以选择是否和用户交互。

From the compiler(webpack) view

待续。。。

参考资料:

【1】官方文档

【2】官方wiki

【3】同事的总结

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读