如何匹配Android Gradle项目依赖项的构建类型?

cop*_*lii 6 android gradle android-gradle-plugin android-productflavors

我有一个包含2个模块的项目:libraryapp

library模块当然是一个库,仅具有releasedebug构建类型。

app模块具有4种口味以及releasedebug构建类型,总共提供8种构建变体。它还声明了对library模块的依赖关系,如下所示:

compile project(path:':library', configuration:'release')

我希望能够library根据应用程序的build变体设置配置:releasebuild变体应使用release库的版本,debugbuild变体应使用debug库的版本。

显而易见的答案是列出这8个变体中的每一个,并进行适当的配置并且可以正常工作,但这并不是最佳的答案:这很丑陋,会使构建脚本过于混乱。

我已经尝试了一些方法project.configurations.all{}applicationVariants.all{},但我无法找到一个明确的方法来设置相关性配置。

有没有更清洁的方法可以做到这一点?

Mik*_*ike 2

如果现在有人仍然遇到此(或类似)问题,您可能需要指定matchingFallbacks要回退到的已解析构建类型或风格,以防您所依赖的库没有匹配的配置。

https://developer.android.com/studio/build/build-variants#resolve_matching_errors

默认情况下,虽然应该有一个debugrelease配置文件,所以要解决OP问题,您只需要删除依赖项声明中的显式配置设置:

// forces release configuration on library
compile project(path:':library', configuration:'release')

// Allows gradle to match buildType from library to 
// what the current module's buildType is:
compile project(path:':library')
Run Code Online (Sandbox Code Playgroud)

开发站点的片段,以防将来发生变化 (.kts):

// In the app's build.gradle file.
android {
    defaultConfig {
        // Do not configure matchingFallbacks in the defaultConfig block.
        // Instead, you must specify fallbacks for a given product flavor in the
        // productFlavors block, as shown below.
    }
    buildTypes {
        getByName("debug") {}
        getByName("release") {}
        create("staging") {
            // Specifies a sorted list of fallback build types that the
            // plugin should try to use when a dependency does not include a
            // "staging" build type. You may specify as many fallbacks as you
            // like, and the plugin selects the first build type that's
            // available in the dependency.
            matchingFallbacks += listOf("debug", "qa", "release")
        }
    }
    flavorDimensions += "tier"
    productFlavors {
        create("paid") {
            dimension = "tier"
            // Because the dependency already includes a "paid" flavor in its
            // "tier" dimension, you don't need to provide a list of fallbacks
            // for the "paid" flavor.
        }
        create("free") {
            dimension = "tier"
            // Specifies a sorted list of fallback flavors that the plugin
            // should try to use when a dependency's matching dimension does
            // not include a "free" flavor. You may specify as many
            // fallbacks as you like, and the plugin selects the first flavor
            // that's available in the dependency's "tier" dimension.
            matchingFallbacks += listOf("demo", "trial")
        }
    }
}
Run Code Online (Sandbox Code Playgroud)