react-admin+NextJS构建失败,List组件引发依赖错误求助
Next.js 14 + react-admin 4.16:
next build 因List组件失败的解决方案 问题定位
这是特定版本组合下的依赖兼容性/构建配置问题,并非react-admin的核心bug。报错本质是构建阶段ra-core无法正确解析react-hook-form的导出,而List组件触发了ra-core中相关代码的加载,最终导致构建失败。
解决方案
1. 统一react-hook-form版本
react-admin 4.16.19依赖特定版本的react-hook-form,若项目中存在版本冲突,会导致构建时导入失败。
- 使用npm的话,在
package.json中添加overrides:"overrides": { "react-hook-form": "^7.45.1" } - 使用yarn的话,添加
resolutions:"resolutions": { "react-hook-form": "^7.45.1" }
执行npm install或yarn install重新安装依赖。
2. 配置Next.js转译react-admin包
Next.js 14默认不会转译第三方库的ES模块,react-admin部分包可能未做完全兼容处理,需手动加入转译列表。
修改next.config.js:
/** @type {import('next').NextConfig} */ const nextConfig = { transpilePackages: ['ra-core', 'ra-ui-materialui', 'react-admin'], // 保留原有配置 }; module.exports = nextConfig;
3. 确保List组件在客户端环境运行
Next.js 14的App Router默认采用SSR,而react-admin的组件依赖客户端上下文,必须标记为客户端组件。
在使用List组件的页面/组件顶部添加'use client'指令:
'use client'; import { List, Datagrid, TextField } from 'react-admin'; export default function UserListPage() { return ( <List> <Datagrid> <TextField source="id" /> <TextField source="name" /> </Datagrid> </List> ); }
4. 清除构建缓存
缓存可能导致依赖解析异常,执行以下命令后重新构建:
rm -rf .next node_modules package-lock.json npm install next build
(yarn用户替换为rm -rf .next node_modules yarn.lock && yarn install && next build)
总结
优先尝试统一依赖版本和标记客户端组件,这两个步骤解决了大部分类似案例的问题;若无效再配置转译包和清除缓存。
内容的提问来源于stack exchange,提问作者中川達貴
相关产品推荐
相关产品推荐

