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

使用Storybook搭配Material-ui时报错无法解析@emotion/react如何解决?

问题解决步骤

方案1:强制指定styled-engine别名

在.storybook/main.js的webpackFinal配置中,给@mui/styled-engine指定绝对路径别名,避免webpack解析到子包node_modules中的错位版本,monorepo场景下需指向根目录的对应依赖:

// .storybook/main.js
const path = require('path');

module.exports = {
  // 保留原有其他配置
  webpackFinal: async (config) => {
    config.resolve.alias = {
      ...config.resolve.alias,
      '@mui/styled-engine': path.resolve(__dirname, '../node_modules/@mui/styled-engine-emotion'),
    };
    return config;
  };
};

方案2:调整webpack模块解析规则

在上述webpackFinal配置中新增模块搜索路径和fallback配置,优先从项目根node_modules查找依赖:

webpackFinal: async (config) => {
  // 优先匹配项目根目录node_modules
  config.resolve.modules = [
    path.resolve(__dirname, '../node_modules'),
    ...config.resolve.modules
  ];
  // 明确指定emotion包的解析路径
  config.resolve.fallback = {
    ...config.resolve.fallback,
    '@emotion/react': path.resolve(__dirname, '../node_modules/@emotion/react'),
    '@emotion/styled': path.resolve(__dirname, '../node_modules/@emotion/styled'),
  };
  return config;
}

方案3:强制依赖版本对齐

删除本地node_modules目录和包管理lock文件后,在package.json中配置版本强制规则,确保mui内部依赖的emotion版本和项目安装版本一致:

  • yarn 场景配置resolutions字段:
{
  "resolutions": {
    "@mui/styled-engine/@emotion/react": "^11.10.0",
    "@mui/styled-engine/@emotion/styled": "^11.10.0"
  }
}
  • npm/pnpm 场景配置overrides字段:
{
  "overrides": {
    "@mui/styled-engine": {
      "@emotion/react": "^11.10.0",
      "@emotion/styled": "^11.10.0"
    }
  }
}

配置完成后重新执行依赖安装命令即可。

方案4:清理冗余的styled-engine实现

检查项目依赖,如果同时安装了@mui/styled-engine-emotion和@mui/styled-engine-sc(styled-components版本),会导致webpack解析冲突,卸载不需要的版本,仅保留emotion版本即可。

方案5:补充emotion babel配置

在.storybook目录下新增babel.config.js,添加emotion转译插件:

module.exports = {
  presets: [
    '@babel/preset-react',
    ['@emotion/babel-preset-css-prop', { autoLabel: 'dev-only' }]
  ],
  plugins: ['@emotion/babel-plugin']
};

内容的提问来源于stack exchange,提问作者Michał Wojas

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 05:06:03