React项目中Floating-UI模块类型错误排查求助
项目package.json配置
{ "name": "lifestyle-monitor-app-ui", "version": "0.1.0", "private": true, "resolutions": { "@types/react": "17.0.2", "@types/react-dom": "17.0.2", "@babel/plugin-transform-block-scoping": "7.20.9" }, "dependencies": { "@emotion/core": "^11.0.0", "@emotion/react": "^11.10.6", "@emotion/styled": "^11.10.6", "@floating-ui/dom": "^1.5.1", "@material-ui/core": "^4.12.4", "@material-ui/lab": "^4.0.0-alpha.61", "@tanstack/react-table": "^8.7.4", "@testing-library/jest-dom": "^5.16.1", "@testing-library/react": "^12.1.2", "@testing-library/user-event": "^13.5.0", "@types/history": "^4.7.11", "@types/react": "^17.0.38", "chart.js": "^3.7.1", "getmdl-select": "^2.0.1", "hashids": "^2.2.11", "material-design-lite": "^1.3.0", "mdl-selectfield": "^1.0.4", "mui-datatables": "^4.3.0", "patch-package": "^8.0.0", "react": "^17.0.2", "react-calendar": "^4.0.0", "react-chartjs-2": "^4.0.1", "react-dom": "^17.0.2", "react-key-index": "^0.1.1", "react-router-dom": "^6.2.1", "react-scripts": "^5.0.1", "react-select": "^5.7.0", "react-table": "^7.7.0", "react-uuid": "^2.0.0", "typescript": "3.8", "uuid": "^9.0.0", "web-vitals": "^2.1.4" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject" }, "eslintConfig": { "extends": [ "react-app", "react-app/jest" ] }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] } }
错误信息
类型不兼容错误:Type 'import("/node_modules/@floating-ui/core/dist/src/types").ReferenceElement' is not assignable to type 'import("/node_modules/@floating-ui/dom/dist/src/types").ReferenceElement',属于跨模块的类型定义冲突问题。
已尝试的解决步骤
- 删除node_modules文件夹并执行
npm install重装依赖 - 更新Visual Studio
- 按照GitHub社区建议将@floating-ui/core替换为@floating-ui/dom
进一步解决建议
1. 升级TypeScript版本
项目当前使用的TypeScript 3.8版本较低,@floating-ui/dom v1.5.1的类型声明可能依赖更高版本的TS语法支持。建议将package.json中的typescript字段修改为"^4.9.5"(该版本与React 17兼容),然后执行:
rm -rf node_modules package-lock.json npm install
2. 修复@types/react版本冲突
package.json的resolutions中指定@types/react为17.0.2,但dependencies中声明的是^17.0.38,版本不一致会导致类型解析混乱。可选择:
- 将
resolutions中的@types/react和@types/react-dom版本修改为^17.0.38,与dependencies保持一致 - 直接移除
resolutions中这两个条目,让npm自动管理兼容版本
3. 清除TypeScript缓存
TS缓存可能残留旧类型定义,执行以下命令清除缓存后重启IDE:
npx tsc --clearCache
4. 强制统一@floating-ui/core版本
部分依赖可能间接引入旧版本的@floating-ui/core,引发类型冲突。在resolutions中添加如下配置,强制所有依赖使用与@floating-ui/dom一致的版本:
"resolutions": { // 原有配置... "@floating-ui/core": "^1.5.1" }
添加后重新执行npm install。
5. 手动兼容类型声明
如果以上方法无效,在项目根目录新建typings/floating-ui.d.ts文件,添加如下内容手动统一类型:
declare module '@floating-ui/dom' { export * from '@floating-ui/core'; }
修改tsconfig.json(无则新建),确保include包含该文件:
{ "include": ["src", "typings"] }
内容的提问来源于stack exchange,提问作者Abhishek Madhusudhan

