Search code examples
gradlegradle-kotlin-dsl

Gradle subproject conditional plugin configuration with gradle kotlin dsl


This is how I've previously configured subprojects in gradle if a certain plugin was present:

subprojects {
    repositories {
        jcenter()
        google()
    }
    plugins.withType(com.android.build.gradle.LibraryPlugin) {
        android {
            compileSdkVersion 29
            ...
        }
    }
}

Now I'm not working with groovy anymore. How can I achieve the same thing with gradle kotlin DSL?

Biggest problem here seems to be to find a way to access the android extension, I can't seem to access it using android nor extensions.findByType(com.android.build.gradle.LibraryExtension::class.java).


Solution

  • I solved this problem by creating a precompiled script plugin, which I applied to all subprojects.

    buildSrc/build.gradle.kts

    plugins {
        `kotlin-dsl`
    }
    
    dependencies {
        implementation("com.android.tools.build:gradle:4.1.2")
    }
    

    buildSrc/src/main/kotlin/android-libary.gradle.kts

    plugins {
        id("com.android.library")
    }
    
    android {
        compileSdkVersion(29)
        ...
    }
    

    subProject/build.gradle.kts

    plugins {
        `android-library`
    }