What is the HMR
When we make changes to the code, WebPack repackages the code and sends the new modules to the browser, which replaces the old modules with new ones and updates our application partially without completely refreshing the page.
What are the advantages of HMR
- It can hot-replace modules in the event of a page refresh, without losing application state in the process
- Only update the changed content, saving time and improving development efficiency
- When modifying JS/CSS in code, it feels like modifying element styles directly in Chrome’s developer tools.
HMR in vUE and React
Vue-loaader already implements HMR, react has this logic at the bottom as well, so no extra setup is required when using Vue and React
if(module.hot) {
module.hot.accept('./hello.js'.function() {
div.innerHTML = hello()
})
}
Copy the code
Whether you need webpack configuration hot configuration HotModuleReplacementPlugin
Note that webpack.HotModuleReplacementPlugin is required to fully enable HMR. If webpack or webpack-dev-server are launched with the –hot option, this plugin will be added automatically, so you may not need to add this to your webpack.config.js. See the HMR concepts page for more information.
The official document says, completely open HMR HotModuleReplacementPlugin is necessary. If Webpack or webpack-dev-server is started with the –hot option, the plugin is automatically added to the webpack configuration.
But in use process found that devServer configured to hot: true, don’t need to add HotModuleReplacementPlugin can also realize the HMR, this is because the webpack dev – this part has determined the logic in the server source code
if (options.hot || options.hotOnly) {
config.plugins = config.plugins || [];
if (
!config.plugins.find(
// Check for the name rather than the constructor reference in case
// there are multiple copies of webpack installed
(plugin) = > plugin.constructor.name === 'HotModuleReplacementPlugin'
)
) {
config.plugins.push(newwebpack.HotModuleReplacementPlugin()); }}Copy the code
This plug-in is automatically added when devServer.hot:true is configured.