最近一直在使用react native中,遇到了很多的坑,同時也學習到了一些移動端的開發經驗。
今天在做一個打包的測試時,遇到了一個問題,打包過程中報錯“Error:Error: Duplicate resources”,什么意思呢,就是打包資源有重復,后來查看了一下,發現打包到android/app/src目錄下的靜態文件重名了。
重現步驟:
1:通過vscode打開項目,運行打包命令
react-native ram-bundle --entry-file index.js --platform android --dev false --bundle-output ./android/app/src/main/assets/index.android.bundle --assets-dest ./android/app/src/main/res/
2:
cd android && ./gradlew assembleRelease
查看android/app/src/mian/res/drawable目錄下靜態資源圖片文件名重復
解決方案
1:打開node_modules/react-native/react.gradle文件,在doFirst塊下添加doLast塊
doLast {
def moveFunc = { resSuffix ->
File originalDir = file("$buildDir/generated/res/react/release/drawable-${resSuffix}");
if (originalDir.exists()) {
File destDir = file("$buildDir/../src/main/res/drawable-${resSuffix}");
ant.move(file: originalDir, tofile: destDir);
}
}
moveFunc.curry("ldpi").call()
moveFunc.curry("mdpi").call()
moveFunc.curry("hdpi").call()
moveFunc.curry("xhdpi").call()
moveFunc.curry("xxhdpi").call()
moveFunc.curry("xxxhdpi").call()
}
2:打開node_modules/react-native/local-cli/bundle/assetPathUtils.js文件,修改getAndroidAssetSuffix函數方法如下
function getAndroidAssetSuffix(scale: number): string {
switch (scale) {
case 0.75: return 'ldpi-v4';
case 1: return 'mdpi-v4';
case 1.5: return 'hdpi-v4';
case 2: return 'xhdpi-v4';
case 3: return 'xxhdpi-v4';
case 4: return 'xxxhdpi-v4';
}
throw new Error('no such scale');
}
3:刪除android/app/src/main/res/drawable-**目錄下面打包進去的靜態資源文件(文件名會比較長)
4:如果采用android studio進行打包,點擊build下clean project,清除打包緩存
5:重新執行打包命令即可打包成功。
參考資料:
1:https://github.com/facebook/react-native/issues/22234
2:https://blog.csdn.net/wyw223/article/details/84311733
