Laravel9+React运行npm run dev报模块找不到错误如何解决
Laravel 9 + React 整合项目 npm run dev 启动报错解决方案
错误1:Module not found: Can't resolve 'laravel-vite-plugin/inertia-helpers'
这个报错是laravel-vite-plugin版本和代码引入规则不匹配导致的:0.6.0及以上版本的插件已经移除了inertia-helpers这个内置导出入口,按照旧版脚手架生成的引入代码会找不到模块。
两种修复方案二选一即可:
- 方案一(适配Laravel9默认脚手架,改动最小):降级插件到兼容版本
执行以下命令:npm uninstall laravel-vite-plugin npm install laravel-vite-plugin@^0.5.4 -D - 方案二(保留高版本插件):调整引入逻辑
先安装Inertia官方依赖:
打开npm install @inertiajs/reactresources/js/app.jsx,把原来第15行的引入语句:
替换为:import { createInertiaApp } from 'laravel-vite-plugin/inertia-helpers'import { createInertiaApp } from '@inertiajs/react'
错误2:Critical dependency: Accessing import.meta directly is unsupported
这个警告是Vite构建规则限制导致的:Vite仅支持直接访问import.meta的静态属性(比如import.meta.env、import.meta.glob),不支持将import.meta整体作为对象赋值、传参、动态取属性。
修复步骤:
- 打开
resources/js/app.jsx,定位到第23行附近,找到直接操作import.meta本身的代码,比如类似const meta = import.meta、const val = import.meta[key]的写法,改成直接访问目标属性即可。 - 如果该警告是第三方依赖抛出、无法直接修改源码,可以在
vite.config.js中添加警告过滤规则:
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(), ], build: { rollupOptions: { onwarn(warning, defaultHandler) { // 过滤import.meta直接访问的警告 if (warning.message.includes('Accessing import.meta directly')) { return } defaultHandler(warning) } } } });
最后校验步骤
所有修改完成后,执行以下命令清缓存重装依赖,避免旧缓存导致问题复现:
rm -rf node_modules package-lock.json npm install npm run dev
内容的提问来源于stack exchange,提问作者masden
相关产品推荐
相关产品推荐

