React Fast Refresh不支持Webpack 5

5uzkadbs  于 2023-04-06  发布在  Webpack
关注(0)|答案(1)|浏览(166)

当我在Webpack 5中使用React Fast Refresh时,整个页面都会刷新,而不仅仅是更改的组件。

EDIT问题是由Webpack配置引起的,解决问题的正确配置将在下面作为答案发布。

6ojccjat

6ojccjat1#

我在研究了官方的例子后发现了这个问题(感谢@基思为我指出了这些例子)。
主要问题是我的index.html包含了一个不需要的bundle.js链接。我的Webpack配置还包含了额外的不必要的配置,如devMiddlewarestatic属性。
下面是我的文件夹结构:

.
├── README.md
├── babel.config.js
├── package-lock.json
├── package.json
├── public
│   └── index.html
├── src
│   ├── Hello.jsx
│   └── index.jsx
└── webpack.config.js

我在这里提供了我的index.htmlwebpack.config.jsbable.config.js,以供将来参考:

网络包配置

const path = require("path");
const ReactRefreshPlugin = require("@pmmmwh/react-refresh-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");

const isDevelopment = process.env.NODE_ENV !== "production";

module.exports = {
  mode: isDevelopment ? "development" : "production",

  devServer: {
    hot: true,

    client: {
      logging: "error",
      overlay: true,
    },
  },

  entry: ["./src/index.jsx"],

  module: {
    rules: [
      {
        test: /\.jsx?$/,
        include: path.join(__dirname, "src"),
        use: "babel-loader",
      },
    ],
  },

  plugins: [
    isDevelopment && new ReactRefreshPlugin(),
    new HtmlWebpackPlugin({
      filename: "./index.html",
      template: "./public/index.html",
    }),
  ].filter(Boolean),

  resolve: {
    extensions: [".js", ".jsx"],
  },
};

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Webpack 5 And React Fast Refresh</title>
  </head>
  <body>
    <div id="app"></div>
  </body>
</html>

数据库配置

module.exports = (api) => {
  // This caches the Babel config
  api.cache.using(() => process.env.NODE_ENV);
  return {
    presets: [
      "@babel/preset-env",
      // Enable development transform of React with new automatic runtime
      [
        "@babel/preset-react",
        { development: !api.env("production"), runtime: "automatic" },
      ],
    ],
    // Applies the react-refresh Babel plugin on non-production modes only
    ...(!api.env("production") && { plugins: ["react-refresh/babel"] }),
  };
};

相关问题