React refresh plugin for Rspack.
First you need to install this plugin and its dependencies:
npm add @rspack/plugin-react-refresh react-refresh -D
# or
yarn add @rspack/plugin-react-refresh react-refresh -D
# or
pnpm add @rspack/plugin-react-refresh react-refresh -D
# or
bun add @rspack/plugin-react-refresh react-refresh -D
Enabling React Fast Refresh functionality primarily involves two aspects: code injection and code transformation.
- Code injection will inject some code from the react-refresh package, as well as some custom runtime code, all of which are integrated in this plugin and can be injected through.
- Code transformation can be added through loaders, such as jsc.transform.react.refresh for swc-loader or the react-refresh/babel for babel-loader.
const ReactRefreshPlugin = require("@rspack/plugin-react-refresh");
const isDev = process.env.NODE_ENV === "development";
module.exports = {
experiments: {
rspackFuture: {
disableTransformByDefault: true,
},
},
// ...
mode: isDev ? "development" : "production",
module: {
rules: [
{
test: /\.jsx$/,
use: {
loader: "builtin:swc-loader",
options: {
jsc: {
parser: {
syntax: "ecmascript",
jsx: true,
},
transform: {
react: {
development: isDev,
refresh: isDev,
},
},
},
},
},
},
],
},
plugins: [isDev && new ReactRefreshPlugin()].filter(Boolean),
};
Compared to the previous approach, this method decouples the React Fast Refresh code injection logic from the transformation logic. The code injection logic is handled uniformly by this plugin, while the code transformation is handled by loaders. This means that this plugin can be used in conjunction with builtin:swc-loader
, swc-loader
, or babel-loader
.
- For usage with
builtin:swc-loader
, you can refer to the example at examples/react-refresh, When using withswc-loader
, simply replacebuiltin:swc-loader
withswc-loader
. - For usage with
babel-loader
, you can refer to the example at examples/react-refresh-babel-loader
Thanks to the react-refresh-webpack-plugin created by @pmmmwh, which inspires implement this plugin.
@rspack/plugin-react-refresh
is MIT licensed.