What is react-refresh-webpack-plugin?
The react-refresh-webpack-plugin is a Webpack plugin that enables hot module replacement (HMR) for React components. It allows developers to see the changes they make to their React components in real-time without having to manually refresh the browser. This plugin is especially useful during development, as it improves productivity by reducing the time spent on manual browser refreshes.
The Problem
When using Webpack 5 with the react-refresh-webpack-plugin, some developers have reported that the hot module replacement feature doesn’t work as expected. The changes made to React components are not reflected in the browser, even though the plugin is correctly configured.
The Solution
After investigating the issue, it was found that there is a specific configuration required to make the react-refresh-webpack-plugin work correctly with Webpack 5. The solution involves making amendments to the optimization and entry sections of the Webpack configuration.
Here is an example of the modified Webpack configuration:
const path = require('path');
const ReactRefreshPlugin = require('@pmmmwh/react-refresh-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const SRC = path.join(__dirname, '..', 'src');
const DIST = path.join(__dirname, '..', 'dist');
const PUBLIC = path.join(__dirname, '..', 'public');
module.exports = (env) => {
return {
mode: 'development',
entry: {
reactRefreshSetup: '@pmmmwh/react-refresh-webpack-plugin/client/ReactRefreshEntry.js',
main: path.join(SRC, 'index.tsx'),
},
output: {
filename: '[name].js',
path: DIST,
},
module: {
rules: [
{
test: /\.tsx?$/,
include: SRC,
use: 'babel-loader',
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader'],
},
],
},
plugins: [
new HtmlWebpackPlugin({
filename: './index.html',
template: path.join(PUBLIC, 'index.html'),
}),
new ReactRefreshPlugin(),
],
resolve: {
extensions: ['.js', '.jsx', '.ts', '.tsx'],
},
};
};
In addition to the above configuration, you also need to modify the devServer and optimization sections:
module.exports = (env) => {
return {
devServer: {
hot: true,
port: 8080,
},
plugins: [
new ReactRefreshPlugin(),
],
optimization: {
runtimeChunk: 'single',
splitChunks: {
chunks: 'all',
name(_, __, cacheGroupKey) {
return cacheGroupKey;
},
},
},
};
};
By making these amendments to the Webpack configuration, the react-refresh-webpack-plugin should work correctly with Webpack 5. The hot module replacement feature will now reflect the changes made to React components in real-time without the need for manual browser refreshes.
Conclusion
In this article, we explored the issue of the react-refresh-webpack-plugin not working correctly with Webpack 5. We provided a solution by making specific amendments to the Webpack configuration. By following the steps outlined in this article, developers can ensure that the hot module replacement feature works as expected when using Webpack 5 with the react-refresh-webpack-plugin.