有条件地将项目包含在 gradle 构建中

Conditionally include project in gradle build

场景:我们有一个 Android 应用程序,其中包含一些不同的可选组件,我们希望能够 include/exclude 根据客户需求和许可。是否可以包含基于构建参数的特定项目 而无需创建所有排列作为构建风格 ?

./gradlew assembleRelease -PincludeFeatureA=true -PincludeFeatureB=false

我想我可以在依赖项中做这样的事情:

dependencies {
  if(includeFeatureA){
    compile project(':featureAEnabled')    
  } else {
    compile project(':featureADisabled')
  }
}

但这似乎不起作用。

更新:考虑到可切换功能的数量,为每个排列使用显式构建变体很麻烦。

例如,给定 3 个可切换的功能,我不想构建这样的风格:

Feature1
Feature1-Feature2
Feature1-Feature3
Feature1-Feature2-Feature3
Feature2
Feature2-Feature3
...

查看 settings.gradle 文件,它可以用来指示要构建的所有项目,在这里您可以阅读设置集并使用它们。


https://docs.gradle.org/current/userguide/build_lifecycle.html https://docs.gradle.org/current/userguide/multi_project_builds.html

这可能会有帮助。

使用Build Variants。您可以基于它们启用或禁用对项目的依赖性您甚至可以对它们使用单​​独的资产或源代码。

我的方案的解决方案是将 if 语句移出依赖项:

假设命令行:

gradlew assembleRelease -PincludeFeatureA

在项目的开头build.gradle,我包括这个:

def featureA_Proj=':featureA_NotIncluded'

然后我有一个这样的任务:

task customizeFeatureA(){
    if(project.hasProperty('includeFeatureA')){
        println 'Including Feature A'
        featureA_Proj=':featureA'
    }
}

最后,在依赖项下,我只包含:

dependencies{
  include(featureA_Proj)
}