Android/Gradle: 根据构建类型有条件地应用插件

Android/Gradle: conditionally apply plugin based on build type

我想做类似的东西(伪代码):

if (BuildType == "release"){
    apply plugin: 'testfairy'
} else if (BuildType == "debug"){
    apply plugin: 'io.fabric'
}

想法是根据构建类型,应用(或不应用)插件。怎么做?

基于Stefan Oehme, a Gradle core developer, he said

Plugins can't be applied to only "part of your project". They are either applied or not. What is the use case where this becomes a problem for you?

所以,答案是这是不可能的。我已经暴露了 my use cases 这会成为一个问题,我会看看大家对此有何评论。

这是我使用的解决方法。想法是引入一个环境变量,只在某些特定的环境中应用插件。

if (System.getenv("PROJECT_ENV") == "Release") {
    apply plugin: 'your plugin'
}

还记得 maven 配置文件吗?你可以使用从 gradle-fury

借来的这个片段来做类似的事情

在你的构建文件中 if (project.hasProperty('profile') && project.profile.split(',').contains("ci")) { //do something }

然后 运行 它什么时候 gradlew -Pprofile=ci

这里有一个完整的例子https://github.com/gradle-fury/gradle-fury/blob/develop/build.gradle

免责声明,我致力于 gradle-fury。为了科学

使用 Gradle 4.6,以下工作:

if (getGradle().getStartParameter().getTaskRequests().toString().contains("Release")) {
    apply plugin: 'testfairy'
} else if (getGradle().getStartParameter().getTaskRequests().toString().contains("Debug")) {
    apply plugin: 'io.fabric'
}

这是我没有使应用程序崩溃的解决方案。当最终调用 class 并出现 Class 未找到异常时,其他解决方案确实崩溃了。

def tasks = gradle.startParameter.taskNames[0] ?: ""
if (tasks.toLowerCase().contains("prod")) {
    println "Firebase-Performance pluign applied..."
    apply plugin: 'com.google.firebase.firebase-perf'
}