如何使用 gradle 和 android 使用 Kotlin DSL 和插件块选择性地应用一些插件

How to optionally apply some plugins using Kotlin DSL and plugins block with gradle and android

我想选择性地应用一些插件来缩短开发时间。

我的意思是我有这个:

app/gradle.build.kts:

plugins {
    id("com.android.application")
    id("com.google.firebase.crashlytics")
}

但我不想一直应用 firebase crashlytics 插件(以及其他插件,如 perf monitor),但如果我尝试访问 plugins 块内的 project,我会得到:

plugins {
    id("com.android.application")

    if (!project.hasProperty("build_fast")) {
        id("com.google.firebase.crashlytics")
    }
}

我得到:

'val Build_gradle.project: Project' can't be called in this context by implicit receiver. Use the explicit one if necessary

所以我的问题是:

  1. 我可以使用 System.getenv("CI") 访问系统环境变量,但是从 android studio 替换这些值目前对我来说有点老套,有人可以展示一种更新方法那些变量?

  2. 如何使用 project.hasPropperty("")

你不能。插件 DSL 限制了你能做什么和不能做什么。这记录在 Limitations of the plugins DSL.

要有条件地应用插件,您必须使用 Project.apply(T):

plugins {
    id("com.android.application")
    id("com.google.firebase.crashlytics") apply false
}

apply false 是必需的,因为我们不想应用该插件,但我们想要该插件可用的类型或 类,因此我们可以以编程方式在一个输入安全方式。

import com.google.firebase.crashlytics.buildtools.gradle.CrashlyticsPlugin

plugins {
    id("com.android.application")
    id("com.google.firebase.crashlytics") apply false
}

apply<CrashlyticsPlugin>()

I can access the System env variables with System.getenv("CI") but replacing those values from android studio is a little bit hacky currently to me, someone can show a way to update those variables?

你不能更新环境(System.getenv()),它是一个不可修改的地图。

How can I do it using project.hasPropperty("")

将其用作您已完成的条件:

import com.google.firebase.crashlytics.buildtools.gradle.CrashlyticsPlugin

plugins {
    id("com.android.application")
    id("com.google.firebase.crashlytics") apply false
}

if (!hasProperty("build_fast")) {
    apply<CrashlyticsPlugin>()
}