You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
constReactRefreshWebpackPlugin=require('@pmmmwh/react-refresh-webpack-plugin');constwebpack=require('webpack');// ... your other importsconstisDevelopment=process.env.NODE_ENV!=='production';module.exports={mode: isDevelopment ? 'development' : 'production',module: {rules: [// ... other rules{test: /\.[jt]sx?$/,exclude: /node_modules/,use: [// ... other loaders{loader: require.resolve('babel-loader'),options: {// ... other optionsplugins: [// ... other pluginsisDevelopment&&require.resolve('react-refresh/babel'),].filter(Boolean),},},],},],},plugins: [// ... other pluginsisDevelopment&&newwebpack.HotModuleReplacementPlugin(),isDevelopment&&newReactRefreshWebpackPlugin(),].filter(Boolean),// ... other configuration options};
前言
HMR 是提升开发体验的一个关键点,最近接触的项目中没有配置这个,导致在开发过程中,每次都要手动刷新,体验不太好,所以折腾一下,发现居然还有这么多门道...
首先介绍一下热重载和热更新的区别:
举个🌰,比如你在某个页面打开了一个弹窗,并且修改了弹窗的内容,如果是热重载(live reload),那么整个页面重新刷新了,弹窗消失,你需要重新触发打开弹窗的操作。而热更新(HMR),刷新弹窗内容的同时,弹窗不关闭,直接可以看到更新后的效果。是不是明显后者开发体验更好?
回到我的踩坑过程,我前后试了三种方式,下面一一介绍一下配置和三者优劣:
live reload
这其实就是上面说的热重载(live reload) 的实现方式了,虽然有点简单粗暴,但是比"刀耕火种"时期的完全需要手动刷新要好点吧。
配置方式
使用的是 webpack-livereload-plugin:
这种方式有一定的代码侵入性,而且因为是热重载(live reload) 的方式,所以开发体验欠佳。
react-hot-loader
使用的是 react-hot-loader,这种方式使用的是热更新(HMR),会检测你的改动点并局部刷新,而且支持 React Hooks。比上面热重载的体验会好一点。
配置方式
这种方式虽然实现了我们的终极目标热更新(HMR),但是代码侵入性较大,需要包使用 hot 包裹入口组件,当是 multiple entries 的场景,就需要改动较多的业务代码。其次,如果使用 ts-loader(没有使用 babel-loader) 去编译 ts 文件的话,使用 react-hot-loader 会不成功,因为 react-hot-loader 依赖于 babel-loader,所以对于使用 ts-loader 的项目来说其实不太友好。
Fast ReFresh
使用的是 React Refresh Webpack Plugin,该插件是 React 官方提供的,将热重载(live reload) 和 HMR 进行了整合,而且相比于 react-hot-loader,容错能力更高。
配置方式
从配置可以看出,只需要改动 webpack 相关配置即可,对业务代码没有侵入性。为什么说它是将热重载(live reload) 和 HMR 进行了整合,主要是它在处理 HMR 时分为了三种情况:
总结
三种方式对比如下:
由上表可以得出,fast refresh 无疑是最优选择。而且 fast refresh 被视为 react-hot-loader 下一代的解决方案,除此之外它还与平台无关,既支持 React Native,也支持 Web,所以最终选择了它。不过它也有一些局限性,比如当设置了 externals,HMR 会失效,所以开发环境可先关闭 externals 配置。
参考资料
The text was updated successfully, but these errors were encountered: