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

使用Gatsby+MUI+Styled-Components时出现@emotion/react缺失错误

Gatsby + MUI + Styled-Components 集成报错:ModuleNotFoundError: Can't resolve '@emotion/react'

问题描述

尝试将Gatsby、MUI和Styled-Components结合使用时,触发错误:ModuleNotFoundError: Module not found: Error: Can't resolve '@emotion/react'。根据MUI文档说明,Styled-Components应该可以作为专属样式方案使用,但实际集成却出现了依赖缺失问题。

复现步骤

  • 执行gatsby new,选择默认配置并指定Styled-Components为样式系统
  • 执行npm install --save @mui/material @mui/styled-engine-sc styled-components完成MUI相关依赖安装
  • 在index.js中导入Button组件:import Button from "@mui/material/Button";,并在页面主div中添加<Button variant="contained">Hello World</Button>
  • 运行gatsby develop时触发上述错误

已尝试的操作及疑问

  • 安装@emotion/react和@emotion/styled后按钮可正常渲染,但无法确认是Styled-Components还是Emotion在实际生效,推测是Emotion
  • 尝试配置webpack别名将@mui/styled-engine指向@mui/styled-engine-sc,但不确定是否和当前问题相关,怀疑需要替换@emotion/styled的别名
  • 查看Gatsby的MUI主题插件,但文档提到npm+Styled-Components组合下SSR无法正常工作,疑惑是否必须使用Yarn

解决方案

方案一:强制MUI使用Styled-Components作为样式引擎

虽然安装了@mui/styled-engine-sc,但MUI默认仍可能尝试加载Emotion依赖。需要通过webpack别名强制指定样式引擎:

  1. 在项目根目录创建gatsby-node.js文件(若已存在则修改),添加以下配置:
exports.onCreateWebpackConfig = ({ actions }) => {
  actions.setWebpackConfig({
    resolve: {
      alias: {
        "@mui/styled-engine": "@mui/styled-engine-sc",
      },
    },
  });
};
  1. 删除node_modules和package-lock.json文件
  2. 重新执行npm install,随后启动gatsby develop即可

方案二:改用Emotion作为样式方案

如果上述配置仍有问题,可直接切换到MUI默认推荐的Emotion:

  • 安装依赖:npm install --save @mui/material @emotion/react @emotion/styled
  • 直接使用MUI组件和@mui/styled中的styled()方法,无需额外配置即可正常运行

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 09:30:57