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

Inertia.js+Vite.js使用{eager: true}报错:无法检测前置代码

解决Laravel11+Inertia+Vite+React中启用预加载时的preamble检测错误

问题根源

给import.meta.glob添加{ eager: true }后,Vite会提前加载匹配的组件,这会打乱React运行时的加载顺序,导致@vitejs/plugin-react无法检测到必要的预编译代码(preamble)。

解决步骤

  • 固定入口文件的依赖加载顺序
    打开resources/js/app.jsx(或你的项目入口文件),确保React、Inertia核心依赖在预加载组件之前导入。示例代码:

    // 先加载核心依赖
    import React from 'react';
    import { createRoot } from 'react-dom/client';
    import { createInertiaApp } from '@inertiajs/react';
    import { resolvePageComponent } from 'laravel-vite-plugin/inertia-helpers';
    
    // 再处理预加载组件
    const pages = import.meta.glob('./Pages/**/*.jsx', { eager: true });
    
    createInertiaApp({
      resolve: (name) => pages[`./Pages/${name}.jsx`].default,
      // ... 其他Inertia配置
    });
    
  • 检查Vite React插件配置
    打开vite.config.js,确保@vitejs/plugin-react使用默认的JSX自动注入配置,不要手动设置jsxRuntime: 'classic'。示例配置:

    import { defineConfig } from 'vite';
    import laravel from 'laravel-vite-plugin';
    import react from '@vitejs/plugin-react';
    
    export default defineConfig({
      plugins: [
        laravel({
          input: 'resources/js/app.jsx',
          refresh: true,
        }),
        react(), // 保持默认配置即可
      ],
    });
    
  • 清除缓存并重新构建
    执行以下命令清除Vite缓存和依赖缓存:

    rm -rf node_modules/.vite
    npm install
    npm run dev
    
  • 优化预加载策略(可选)
    如果不需要全局预加载所有页面组件,可以只对特定组件启用eager,或者改用Inertia官方推荐的路由层面预加载——在Laravel路由中定义->withInertiaPreload(),避免全局glob eager带来的顺序问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 16:42:04