[英 => 中] webpack 中的 HMR
原文地址: 本人翻译水平有限,译文中难免存在错误,欢迎指出并及时纠正。 Hot Module Replacement (热模块替换)Hot Module Replacement (HMR) exchanges,adds,or removes while an application is running without a page reload. This allows you to speed up development time by updating individual modules when they are changed without refreshing the page.
How Does It Work? (它是如何工作的?)From The App View (从 APP 视角)
You can set up HMR so that this process happens automatically,or you can choose to require user interaction for updates to occur.
From The Compiler (webpack) View (从编译器 (webpack) 视角)In addition to the normal assets,the compiler needs to emit an "update" to allow updating from previous version to the new version. The "update" consists of two parts:
The manifest contains the new compilation hash and a list of all update chunks.
Each update chunk contains code for all updated modules in the respective chunk (or a flag indicating that the module was removed)
The compiler makes sure that module IDs and chunk IDs are consistent between these builds. It typically stores these IDs in memory (for example,when using webpack-dev-server),but it's also possible to store them in a JSON file.
From The Module View (从模块视角)HMR is an opt-in feature that only affects modules containing HMR code. One example would be patching styling through the . In order for patching to work,style-loader implements the HMR interface; when it receives an update through HMR,it replaces the old styles with the new ones.
Similarly,when implementing the HMR interface in a module,you can describe what should happen when the module is updated. However,in most cases,it's not mandatory to write HMR code in every module. If a module has no HMR handlers,the update bubbles up. This means that a single handler can handle an update to a complete module tree. If a single module in this tree is updated,the complete module tree is reloaded (only reloaded,not transferred).
From The HMR Runtime View (Technical) (从 HMR 运行时视角 (技术性的) )For the module system runtime,additional code is emitted to track module
On the management side,the runtime supports two methods:
A
The
Afterwards,all invalid modules are disposed (via the dispose handler) and unloaded. The current hash is then updated and all "accept" handlers are called. The runtime switches back to the
What can I do with it? (我可以用它做什么?)You can use it in development as a LiveReload replacement. supports a hot mode in which it tries to update with HMR before trying to reload the whole page. See how to implement as an example.
Some loaders already generate modules that are hot-updatable. For example,the
webpack's power lies in its customizability,and there are many ways of configuring HMR depending on the needs of a particular project.
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |