react-select依赖的@emotion启动报options未定义错误如何解决
问题根因
该报错本质是**@emotion 依赖版本冲突**导致:react-select@4.3.1 依赖的 @emotion 系列包版本为 ^11.1.1,当项目中其他依赖引入了不兼容的 @emotion/cache 版本,或是包管理器扁平化依赖时出现版本错配,就会出现调用 createCache 时没有传入 options 参数的问题。
解决方法
- 方法1:锁定@emotion相关依赖的兼容版本
在package.json的对应配置字段中指定和react-select@4.3.1适配的@emotion版本:
若使用yarn包管理器,添加resolutions字段:
若使用npm >=8.3.0或pnpm包管理器,添加"resolutions": { "@emotion/cache": "^11.4.0", "@emotion/react": "^11.4.1" }overrides字段:
配置完成后删除node_modules文件夹和对应的lock文件(yarn.lock/package-lock.json/pnpm-lock.yaml),重新执行依赖安装命令即可。"overrides": { "@emotion/cache": "^11.4.0", "@emotion/react": "^11.4.1" } - 方法2:升级react-select版本
若业务允许升级组件,直接将react-select升级到最新v5版本即可解决依赖适配问题:# npm npm install react-select@latest # yarn yarn add react-select@latest - 方法3:显式配置Emotion Cache兜底
若不想修改依赖版本,可以在项目入口文件手动创建合法的emotion cache,强制react-select使用该配置:
首先安装相关依赖:
之后修改入口文件(一般为index.jsx/index.tsx)代码,用CacheProvider包裹根组件:npm install @emotion/react @emotion/cacheimport { CacheProvider } from '@emotion/react'; import createCache from '@emotion/cache'; const emotionCache = createCache({ key: 'react-select-cache' }); ReactDOM.render( <CacheProvider value={emotionCache}> <App /> </CacheProvider>, document.getElementById('root') );
内容的提问来源于stack exchange,提问作者ahorak
相关产品推荐
相关产品推荐

