使用react-native-clean-project后yarn install出现TypeScript依赖错误怎么办?
使用react-native-clean-project清理React Native项目后,执行yarn install时出现如下错误:
warning ../../../../../../package.json: No license field
$ yarn tsc
warning ../../../../../../package.json: No license field
$ /Users/username/Library/Caches/Yarn/v6/.tmp/81343329c03468d8a899f4bb8612d8b8.0999079ce5055d5008e3c67ffe97b2756c0c741f.prepare/node_modules/.bin/tsc
src/WebView.android.tsx:340:7 - error TS2605: JSX element type 'NativeWebViewAndroid' is not a constructor function for JSX elements.
The types returned by 'render()' are incompatible between these types.
Type 'React.ReactNode' is not assignable to type 'import("/Users/username/node_modules/@types/react/index").ReactNode'.
Type '{}' is not assignable to type 'ReactNode'.
Type '{}' is not assignable to type 'ReactPortal'.340 <NativeWebView
~~~~
341 key="webViewKey"
~~~~
...
356 {...nativeConfig.props}
~~~~~~~
357 />
~~
已尝试清理yarn缓存、重新安装yarn,问题仍未解决,求解决建议。
统一React类型依赖版本
错误核心是React.ReactNode类型不兼容,大概率是项目中存在多版本的@types/react或react依赖。先执行命令检查依赖树:yarn list @types/react若发现多个版本,在
package.json中添加resolutions字段强制统一版本(替换为你项目React版本对应的类型版本):"resolutions": { "@types/react": "^18.2.0" }之后重新执行
yarn install。检查
react-native-webview版本兼容性
错误出现在WebView.android.tsx,确认react-native-webview版本与你的React Native版本是否匹配。查看package.json中的对应版本,对照官方兼容性说明调整版本:yarn add react-native-webview@x.x.x彻底清理依赖后重装
删除残留的依赖文件和锁文件,重新安装:rm -rf node_modules rm yarn.lock yarn cache clean --all yarn install调整TypeScript配置
检查tsconfig.json的compilerOptions,确保React相关配置正确:{ "compilerOptions": { "jsx": "react-native", "moduleResolution": "node", "target": "esnext", "lib": ["esnext", "dom"], "skipLibCheck": true } }skipLibCheck可跳过库类型文件的检查,避免不同库之间的类型冲突。重新链接原生模块
清理操作可能导致原生模块链接异常,执行以下命令修复:npx react-native link react-native-webview # Android 额外操作 cd android && ./gradlew clean && cd .. # iOS 额外操作 cd ios && pod deintegrate && pod install && cd ..
内容的提问来源于stack exchange,提问作者Berkay Atasoy

