Gradle: 如何定义多种口味的共同依赖?

Gradle: How to define common dependency for multiple flavors?

我的应用有 3 种风格(freepaidspecial)并且有一个依赖项 LIB_1 只需要 free 风格和其他依赖项LIB_2 paidspecial 口味都需要。

所以,我的问题是如何在 build.gradle 文件中定义这些依赖项?

目前,我这样定义它们:

dependencies {
    freeImplementation 'LIB_1'
    paidImplementation 'LIB_2'
    specialImplementation 'LIB_2'
}

有没有更好的方法来定义它们而不是为不同的口味复制相同的依赖关系?

是的,根据 android gradle dependency management 的文档,这是声明特定风味依赖项的唯一方法。

如果您在多模块项目中(并且您不想在每个子模块中重复这些行),您还可以使用 [=17= 中的 subproject 块定义这些依赖项] 根项目:

subprojects {
    //all subprojects` config
}
//or
configure(subprojects.findAll {it.name != 'sample'}) {
    // subprojects that their name is not "sample"
}