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

在传统后端加载Vite React-TS应用时遇@vitejs/plugin-react预检测错误

解决@vitejs/plugin-react无法检测preamble的问题

核心原因

这个错误是因为@vitejs/plugin-react编译组件时,会检查全局变量__vite_plugin_react_preamble_installed__是否存在,若未检测到就会抛出该错误。你的配置里虽然手动添加了预加载脚本,但可能存在语法或执行顺序问题,导致全局变量未正确挂载。

具体修复步骤

  • 修正预加载脚本的语法
    你原来的脚本代码缺少分号,可能导致JS解析错误,无法正确初始化全局变量。把代码拆分为独立语句并添加分号:

    <script type="module">
      import RefreshRuntime from 'http://localhost:5173/@react-refresh';
      RefreshRuntime.injectIntoGlobalHook(window);
      window.$RefreshReg$ = () => {};
      window.$RefreshSig$ = () => (type) => type;
      window.__vite_plugin_react_preamble_installed__ = true;
    </script>
    
  • 严格控制脚本加载顺序
    必须保证预加载脚本最先执行,然后是@vite/client,最后才是你的应用入口main.tsx,正确的HTML结构应该是:

    <head>
      <!-- 预加载脚本放在最前面 -->
      <script type="module">
        import RefreshRuntime from 'http://localhost:5173/@react-refresh';
        RefreshRuntime.injectIntoGlobalHook(window);
        window.$RefreshReg$ = () => {};
        window.$RefreshSig$ = () => (type) => type;
        window.__vite_plugin_react_preamble_installed__ = true;
      </script>
      <!-- 然后加载@vite/client -->
      <script type="module" src="http://localhost:5173/@vite/client"></script>
    </head>
    <body>
      <div id="root"></div>
      <!-- 最后加载应用入口 -->
      <script type="module" src="http://localhost:5173/src/main.tsx"></script>
    </body>
    
  • 调整Vite服务器配置
    确保Vite服务允许跨域(如果后端和Vite端口不同),并指定正确的origin:

    // vite.config.ts
    import { defineConfig } from 'vite';
    import react from '@vitejs/plugin-react';
    
    export default defineConfig({
      plugins: [react()],
      server: {
        cors: true,
        origin: 'http://localhost:5173' // 与你HTML中使用的Vite地址完全一致
      }
    });
    
  • 移除不必要的polyfill导入
    import 'vite/modulepreload-polyfill'在后端集成场景下不是必需的,反而可能干扰预加载流程,建议先移除它再测试。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 12:25:05