You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Office插件中从react-hot-loader迁移至react-refresh的方案求助

迁移至React Refresh的可行步骤

1. 安装必要依赖

先移除旧的react-hot-loader,再安装React Refresh相关工具:

npm uninstall react-hot-loader
npm install -D react-refresh @pmmmwh/react-refresh-webpack-plugin babel-plugin-react-refresh

2. 修改Webpack配置文件(webpack.config.js)

完成以下几处调整:

  • 移除React Hot Loader相关配置
    删除entry.taskpane中的"react-hot-loader/patch",同时删掉module.rules里babel-loader之前的"react-hot-loader/webpack"加载器。
  • 添加React Refresh Webpack插件
    在文件顶部导入插件:
    const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin');
    
    然后在plugins数组中,仅在开发环境注入该插件:
    plugins: [
      // ... 原有插件
      dev && new ReactRefreshWebpackPlugin(),
    ].filter(Boolean), // 过滤生产环境下的无效值
    
  • 更新Babel Loader配置
    修改babel-loader的options,仅在开发环境添加react-refresh插件:
    {
      test: /\.jsx?$/,
      use: [
        {
          loader: "babel-loader",
          options: {
            presets: ["@babel/preset-env"],
            ...(dev ? { plugins: ["babel-plugin-react-refresh"] } : {}),
          },
        },
      ],
      exclude: /node_modules/,
    },
    
  • 优化DevServer配置
    确认devServer中hot为true,可添加hotOnly: true避免页面强制刷新:
    devServer: {
      hot: true,
      hotOnly: true,
      // ... 原有配置
    },
    

3. 修改入口文件(index.js)

彻底移除React Hot Loader的所有痕迹,调整渲染逻辑:

import App from "./components/App";
import { initializeIcons } from "@fluentui/font-icons-mdl2";
import * as React from "react";
import * as ReactDOM from "react-dom";
/* global document, Office */

initializeIcons();

let isOfficeInitialized = false;

const title = "Contoso Task Pane Add-in";

const render = (Component) => {
  ReactDOM.render(
    <Component title={title} isOfficeInitialized={isOfficeInitialized} />,
    document.getElementById("container")
  );
};

Office.onReady(() => {
  isOfficeInitialized = true;
  render(App);
});

render(App);

// 移除原有的module.hot.accept逻辑,React Refresh会自动处理组件热更新

4. 验证迁移结果

启动开发服务器:

npm start

修改任意React组件(如App.js),检查Office任务窗格是否自动刷新且保留组件状态。


内容的提问来源于stack exchange,提问作者Jannik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 05:10:32