Android/Gradle: conditionally apply plugin based on build type

不羁的心 提交于 2019-12-30 05:56:40

问题


I would like to make something like (pseudo code):

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

The idea is that based on the build type, apply (or not) a plugin. How to do it ?


回答1:


With Gradle 4.6, the following works:

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



回答2:


Based on 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?

So, the answer is this is not possible. I have exposed my use cases where this is becomes a problem and I'll see what hi says about it.




回答3:


Here is a workaround solution I used. The idea is to introduce an Env variable and only apply the plugin in some specific env.

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



回答4:


Remember maven profiles? You can do something similar using this snippet which was borrowed from gradle-fury

in your build file if (project.hasProperty('profile') && project.profile.split(',').contains("ci")) { //do something }

then run it when gradlew -Pprofile=ci

There's a complete example here https://github.com/gradle-fury/gradle-fury/blob/develop/build.gradle

Disclaimer, i work on gradle-fury. for science




回答5:


Here was the solution I had that did not crash the app. Other solutions did crash when the class was finally called with a Class not found exception.

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


来源:https://stackoverflow.com/questions/36039793/android-gradle-conditionally-apply-plugin-based-on-build-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!