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

NX+Next.js项目共享组件库用react-hook-form触发__emotion_styles错误求助

解决NX项目中共享组件库使用react-hook-form + MUI出现的__emotion_styles未定义错误

1. 统一Emotion与MUI依赖版本

  • 确认项目根目录和组件库的package.json中,@emotion/react、@emotion/styled、@mui/material等相关依赖版本完全一致。NX monorepo中多版本依赖会导致运行时上下文冲突,引发这类随机错误。
  • 运行nx dep-graph查看依赖树,排查重复依赖,用npm dedupe或yarn dedupe合并同版本依赖。

2. 配置NX共享依赖规则

  • 在nx.json中添加共享依赖配置,强制整个monorepo使用同一版本的核心依赖:
{
  "npmScope": "your-project-scope",
  "sharedDependencies": {
    "@emotion/react": "*",
    "@emotion/styled": "*",
    "react-hook-form": "*",
    "@mui/material": "*"
  }
}
  • 执行nx reset清除NX缓存,再重新构建项目。

3. 调整组件库的构建配置

  • 如果组件库使用SWC构建,在.swcrc中添加Emotion支持:
{
  "jsc": {
    "transform": {
      "react": {
        "runtime": "automatic",
        "importSource": "@emotion/react"
      }
    }
  }
}
  • 如果用Babel构建,确保babel.config.json中包含Emotion插件:
{
  "plugins": ["@emotion/babel-plugin"]
}
  • 注意不要开启过度混淆或tree shaking,避免Emotion的样式标记被误删。

4. 组件库依赖设为Peer Dependencies

  • 修改组件库的package.json,将react、react-dom、@emotion/react等依赖移至peerDependencies,避免组件库与主应用出现多个React或Emotion实例:
"peerDependencies": {
  "react": "^18.0.0",
  "react-dom": "^18.0.0",
  "@emotion/react": "^11.10.0",
  "@emotion/styled": "^11.10.0",
  "@mui/material": "^5.10.0",
  "react-hook-form": "^7.40.0"
}
  • 确保主应用已安装这些peer依赖,执行npm install完成依赖安装。

5. 彻底清除缓存并重构建

  • 执行以下命令清理缓存、删除构建产物,重新安装依赖并构建:
nx clear-cache
rm -rf node_modules .next dist
npm install
nx run-many --target=build --all

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 16:22:22