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

求助解决@emotion/react重复加载警告问题

排查@emotion/react重复加载警告方案

组件包构建环节检查

  • peerDependencies版本范围要精准:打开组件包的package.json,确保@emotion/react(及@emotion/styled如果用到)的版本范围和主项目安装的版本完全匹配,别用^这种可能拉取不同小版本的符号,比如直接写"@emotion/react": "11.11.3",避免版本差异触发多实例加载。
  • 确认Vite外部依赖配置生效:组件包的vite.config.ts里,build.rollupOptions.external必须包含@emotion/react,不然打包时会把它塞进组件包,导致主项目加载两份。示例配置:
    export default defineConfig({
      build: {
        lib: {
          entry: 'src/index.ts',
          name: 'YourComponentLib',
          fileName: (format) => `your-lib.${format}.js`
        },
        rollupOptions: {
          external: ['react', 'react-dom', '@emotion/react', '@emotion/styled'],
          output: {
            globals: {
              react: 'React',
              'react-dom': 'ReactDOM',
              '@emotion/react': 'EmotionReact'
            }
          }
        }
      }
    })
    
  • dedupe配置不能漏:组件包Vite配置的resolve.dedupe要明确指定@emotion/react,强制构建时只保留一个实例:
    resolve: {
      dedupe: ['@emotion/react']
    }
    
  • Babel插件只在开发环境用:组件包的@emotion/babel-plugin是devDependencies,别让它参与生产包构建。如果有单独的babel配置文件,要限定插件只在dev环境启用:
    // babel.config.js
    module.exports = {
      env: {
        development: {
          plugins: ['@emotion/babel-plugin']
        }
      }
    }
    

主项目使用环节检查

  • 排查多版本依赖:在主项目根目录跑npm ls @emotion/react或yarn list @emotion/react,看输出里有没有多个版本的@emotion/react。有的话直接用npm的overrides或yarn的resolutions强制统一版本:
    npm的package.json加:
    "overrides": {
      "@emotion/react": "11.11.3"
    }
    
    yarn的package.json加:
    "resolutions": {
      "@emotion/react": "11.11.3"
    }
    
  • Vite React插件配置要统一:主项目的vite.config.ts里,React插件必须设置jsxImportSource为@emotion/react,同时配置babel插件和dedupe:
    import { defineConfig } from 'vite'
    import react from '@vitejs/plugin-react'
    
    export default defineConfig({
      plugins: [
        react({
          jsxImportSource: '@emotion/react',
          babel: {
            plugins: ['@emotion/babel-plugin']
          }
        })
      ],
      resolve: {
        dedupe: ['@emotion/react']
      }
    })
    
  • 检查组件包引入路径:确认主项目加载的是组件包的打包产物,不是源码。看组件包package.json的main、module、types字段,是否指向dist目录下的文件,比如:
    "main": "./dist/your-lib.umd.js",
    "module": "./dist/your-lib.es.js",
    "types": "./dist/index.d.ts"
    
  • 清缓存重装依赖:把主项目和组件包的node_modules、package-lock.json/yarn.lock都删掉,重新执行npm install或yarn install,缓存的旧依赖可能导致重复加载。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 21:30:57