Webpack Hot Update, also known as Hot Module Replacement (HMR), is a process that updates, adds, or removes modules while the application is running without a full page refresh. This feature is highly valuable for frontend development as it significantly enhances development efficiency by enabling developers to see real-time effects of code changes.
Here is an overview of its working principle and process:
Hot Update Principle
1. Server and Client Communication via WebSocket
HMR functionality relies on WebSocket, which enables the server to push real-time updates to the client. When your application is running, the Webpack dev server initiates a WebSocket server to monitor file changes.
2. Hot Module Replacement Plugin
Webpack utilizes the HotModuleReplacementPlugin plugin to implement module hot replacement. This plugin injects HMR runtime code during the compilation process.
3. Manifest File
Upon build completion, Webpack generates a manifest file that records the latest version number for each module. This file informs the HMR runtime about which files have been modified.
4. Update Lifecycle
HMR features a lifecycle of events that allow developers to control hot replacement handling, such as module.hot.accept, module.hot.decline, and module.hot.dispose.
Hot Update Process
1. File Modification
Developers modify one or more files, and Webpack detects these changes to recompile the affected modules.
2. Compilation Build
Webpack recompiles the modified modules and generates a new manifest file along with updated module code.
3. File Change Notification
The Webpack dev server sends an update signal via WebSocket, typically including the hash values of changed modules, to the client.
4. Receiving Updates
After receiving the update signal, the client requests update information—such as the new manifest file—through the HMR runtime.
5. Requesting Update Files
The client retrieves the latest module code based on the manifest file, usually via JSONP requests.
6. Replacing Modules
The HMR runtime parses the update information (manifest) to identify modules for replacement and executes the replacement. If module hot replacement handling functions are configured (e.g., via module.hot.accept), these functions are invoked first to manage the replacement logic.
7. View Update
Once the module update is complete, changes to components or styles are immediately reflected in the application's UI without requiring a full page refresh.
Example
For instance, when a developer modifies a React component's code and saves it, Webpack recompiles the module and pushes the update to the client. The client then uses libraries like React Hot Loader to seamlessly replace the React component, allowing developers to instantly see the changes.
This is the fundamental principle and process of hot updates. In daily development, this functionality significantly reduces redundant loading times, improving development experience and efficiency.