當你在看到這篇博客的時候,可能正在為RN無法運行而感到頭疼。我還是很遺憾地想說,我並不能保證以下方法能夠成功,畢竟這些只是我的經歷。
方法1.排錯
根據報錯提示進行排錯,適合偶然出現的小錯誤,是最直接的方法。
如果是接手別人遺留的無法運行的項目,那就看運氣了,因為一個錯誤解決了,還有另一個錯誤等着你。
可以看一下我對某個項目的排錯筆記,可能看起來挺亂的,畢竟當時是寫給自己看的
------分割線:排錯筆記-------
react-native run-android的報錯信息不夠詳細時,可在android studio中build,並在android目錄下運行gradlew [報錯信息] --stacktrace
(gradlew [報錯信息] --stacktrace,例如報錯:app:processDebugManifest FAILED就運行gradlew processDebugManifest --stacktrace,一般如此,但也不一定是這樣,具體參照網上資料)查看詳細記錄,有時會給出操作意見。
參考:Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get m
參考:Manifest merger failed with multiple errors, see logs問題處理
- 遇到的錯誤
1、:app:processDebugManifest FAILED
參考:react-native run-android Build failed報錯(:app:processDebugManifest FAILED)
android目錄下運行gradlew processDebugManifest --stacktrace
,看到給出了建議Suggestion: add 'tools:replace="android:appComponentFactory"' to application element at AndroidManifest.xml... 根據建議添加后報錯誤2
2、Error: tools:replace specified at line:14 for attribute android:appComponentFactory, but no new value specified
E:\Android\Job\TestDemoProject\github\BaseApplication\BaseApplication\app\src\main\AndroidManifest.xml
Error: Validation failed, exiting
參考:解決 導入三方時出現: appComponentFactory 錯誤
解決:
<application
tools:replace="android:appComponentFactory" //除了這行之外
android:appComponentFactory="任意字符" //還要加上這一行
3、:app:transformDexArchiveWithExternalLibsDexMergerForDebug
android studio中在android目錄下運行gradlew transformDexArchiveWithExternalLibsDexMergerForDebug --stacktrace
查看詳細報錯。
參考:jar沖突 - app:transformDexArchiveWithExternalLibsDexMergerForDebug
參考:問題:com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex
4、:app:transformClassesWithMultidexlistForDebug
Duplicate zip entry [97.jar:androidx/versionedparcelable/CustomVersionedParcelable.class]
參考資料
dependencies {
configurations {
all*.exclude group: 'androidx.core', module: 'core'
}
}
5、:app:transformResourcesWithMergeJavaResForDebug
More than one file was found with OS independent path 'META-INF/***'
參考資料
android{
...
...
packagingOptions {
exclude 'META-INF/DEPENDENCIES'
}
}
6、react-native run-android Could not read path...(常見)
參考資料
cd android && gradlew clean
或者刪app目錄下的build文件夾
7、Error type 3
Error: Activity class {com.aiworks/com.aiworks.MainActivity} does not exist.
--------分割線---------
以上是android調試,到最后問題7的時候項目其實已經build successful了,然而就報了這么一個錯不給我跑,排錯就這么失敗了。
方法2.遷移
- 重新初始化一個RN項目,並確保能運行
- 在新項目中重新安裝第三方組件和依賴
對於需要修改android或ios代碼的第三方組件,最好是單獨安裝,安裝並配置好后確保項目能夠運行,若無法運行可先略過,先安裝其他依賴。其他不需要額外配置的依賴,可直接寫入package.json並npm install 或 yarn。 - 拷貝舊項目的js代碼,進行最終調試。
我通過方法2成功地讓項目跑起來了。
注意事項
- 某些第三方組件的配置文檔可能並不適用最新的RN版本,比如現在RN已經不需要手動link了,並且MainApplication.java中的getPackages() 方法中不需要再手動添加包了。
- ios可以使用cocoaPods來管理第三方組件,在ios/目錄下運行pod install就可以安裝第三方組件,cocoaPods需要 .podspec文件,年代比較久遠的第三方組件可能沒有這個文件,就需要自己手動加,
示例:https://github.com/rt2zz/react-native-contacts/blob/master/react-native-contacts.podspec