Background
I used React to enable HMR for webpack and webpack-dev-server using the following modules, but I didn’t like it because the Functional Component wasn’t updated properly. Since it’s a big deal, I will use react-refresh provided by react recently to make it a cool development environment. Please note that the writing style before the change seems to be old in the first place.
- @ hot-loader / react-dom
- react-hot-loader
Overview
Remove react-hot-loader and install react-refresh-webpack-plugin .
the manner of the introduction of-Refresh-React Webpack-Plugin, for people who guide came from the react-hot-loader, will continue to make changes in accordance with.
Before
webpack.dev.js
module: {
rules: [
{
test: /\.(j|t)sx?$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
},
},
/* Omission */
resolve: {
alias: {
"react-dom": "@hot-loader/react-dom",
index.tsx
import React from "react"
import ReactDOM from "react-dom"
function renderApp() {
ReactDOM.render(<App />, document.querySelector("#root"))
}
if (module.hot) {
module.hot.accept("components/App/App", () => {
renderApp()
})
}
App.ts
import { hot } from "react-hot-loader/root"
import React from "react"
/* Omission */
export default hot(App)
After
- Remove alias for @ hot-loader / react-dom
- Added react-refresh / babel to babel-loader plugins
- Added ReactRefreshWebpackPlugin to plugins
webpack.dev.js
const ReactRefreshWebpackPlugin = require("@pmmmwh/react-refresh-webpack-plugin")
module: {
rules: [
{
test: /\.(j|t)sx?$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: {
plugins: [require.resolve("react-refresh/babel")],
},
plugins: [
new ReactRefreshWebpackPlugin()
Remove module.hot.accept()
index.tsx
import React from "react"
import ReactDOM from "react-dom"
function renderApp() {
ReactDOM.render(<App />, document.querySelector("#root"))
}
renderApp()
Remove hot()
import React from "react"
export default App
Remove react-hot-loader/babel from .babelrc
.babelrc
- "react-hot-loader/babel",
Afterword
It was easy. It feels good to update the Functional Component without reloading.
Discussion about this post