react native中一次錯誤排查 Error:Error: Duplicate resources

最近一直在使用react native中,遇到了不少的坑,同時也學習到了一些移動端的開發經驗。javascript

今天在作一個打包的測試時,遇到了一個問題,打包過程當中報錯「Error:Error: Duplicate resources」,什麼意思呢,就是打包資源有重複,後來查看了一下,發現打包到android/app/src目錄下的靜態文件重名了。java

重現步驟:node

1:經過vscode打開項目,運行打包命令react

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:android

cd android && ./gradlew assembleRelease

 

查看android/app/src/mian/res/drawable目錄下靜態資源圖片文件名重複git

 

解決方案github

1:打開node_modules/react-native/react.gradle文件,在doFirst塊下添加doLast塊react-native

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-**目錄下面打包進去的靜態資源文件(文件名會比較長)app

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

相關文章
相關標籤/搜索