react native中一次错误排查 Error:Error: Duplicate resources

最近一直在使用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

猜你喜欢

转载自www.cnblogs.com/sk-3/p/10720933.html