Gradle:如何为多个Flavor定义共同的依赖项?

3
我的应用有3种不同的版本(免费版付费版特别版),其中免费版需要一个名为LIB_1的依赖库,而付费版特别版则需要另一个名为LIB_2的依赖库。

那么,我的问题是如何在build.gradle文件中定义这些依赖关系呢?

目前,我是这样定义它们的:

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

有没有更好的方法来定义它们,而不是为不同的风味重复相同的依赖项?

2个回答

0

是的,可以避免在不同版本中重复依赖项,就像我在这里的回答中所描述的那样:https://dev59.com/DqTia4cB1Zd3GeqP9iyK#75083956

实用工具

只需在dependencies块之前添加以下函数:

/** Adds [dependency] as a dependency for the flavor [flavor] */
dependencies.ext.flavorImplementation = { flavor, dependency ->
    def cmd = "${flavor}Implementation"
    dependencies.add(cmd, dependency)
}

/** Adds [dependency] as a dependency for every flavor in [flavors] */
dependencies.ext.flavorsImplementation = { flavors, dependency ->
    flavors.each { dependencies.flavorImplementation(it, dependency) }
}

使用方法

您可以像这样使用此实用程序:

dependencies {
    ...
    def myFlavors = ["flavor1", "flavor2", "flavor3"]
    flavorsImplementation(myFlavors, "com.example.test:test:1.0.0")
    flavorsImplementation(myFlavors, project(':local'))
    ...
}

工作原理

这个实用程序的关键是gradle的dependencies.add API,它有两个参数:

  1. 依赖类型,例如implementationapiflavor1Implementation。这可以是一个字符串,允许我们使用字符串操作来动态创建此值。
  2. 依赖本身,例如"com.example.test:test:1.0.0"project(':local')

使用这个API,你可以动态地添加依赖项,具有相当大的灵活性!


0

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

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

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

如果我理解正确的话,那么我需要为每种口味复制依赖关系? - y.allam

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接