最近(2022年11月4日)很多 react-native 项目上都出现了打包失败或者是开发环境无法启动的问题,报错内容很多:找不到符号、方法不会覆盖或者实现超类型的方法、程序包 XXX 不存在等。但点进源码可以发现几乎都是 com.facebook.react
下的某个包找不到导致的。
react native 大于0.63 的直接删除 node_modules 然后重新yarn install,然后进入android 目录
清除缓存 grawlew clean 重新yarn android即可
react native 小于0.63 的 在 android\build.gradle
添加如下内容
def REACT_NATIVE_VERSION = new File(['node', '--print',"JSON.parse(require('fs').readFileSync(require.resolve('react-native/package.json'), 'utf-8')).version"].execute(null, rootDir).text.trim())allprojects {configurations.all {resolutionStrategy {// Remove this override in 0.65+, as a proper fix is included in react-native itself.force "com.facebook.react:react-native:" + REACT_NATIVE_VERSION}}repositories {
大致意思就是获取到当前使用的 react-native 版本,然后把所有依赖项目的 rn 都覆盖成这个版本
问题的起因来自于早期的 react-native 模板项目,其中构建文件(.\android\build.gradle
)中包含这么一行配置:
implementation 'com.facebook.react:react-native:+'
可以看到这里配置了 获取当前依赖库里能找到的最高等级的 react-native 版本,这些依赖跟react native 版本不匹配导致构建失败
如果遇到获取资源失败试着在android\build.gradle里面修改
把 jcenter() 修改成 mavenCentral(),jcenter即将停止服务