Home > Mobile >  Moving gradle kts functions to a separate file
Moving gradle kts functions to a separate file

Time:09-08

Previously with Groovy, you could easily move parts of your build.gradle to separate files. But now using the Kotlin DSL I get unresolved references and I can't seem to figure out why.

If I have this in my app/build.gradle.kts file, everything compiles nicely.

/**
 * Apply shared configurations to the android modules.
 */
fun com.android.build.gradle.BaseExtension.baseConfig() {
    plugins.withType<com.android.build.gradle.api.AndroidBasePlugin> {
        configure<com.android.build.gradle.BaseExtension> {
            defaultConfig {
                compileOptions {

                    compileSdkVersion(33)
                    defaultConfig {
                        minSdk = 23
                        targetSdk = 33
                    }

                    sourceCompatibility = JavaVersion.VERSION_11
                    targetCompatibility = JavaVersion.VERSION_11
                }
            }
        }
    }

    tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinJvmCompile> {
        kotlinOptions.jvmTarget = "11"
    }
}

/**
 * Apply configuration settings that are shared across all modules.
 */
fun PluginContainer.applyBaseConfig(project: Project) {
    whenPluginAdded {
        when (this) {
            is com.android.build.gradle.internal.plugins.AppPlugin -> {
                project.extensions
                    .getByType<com.android.build.gradle.AppExtension>()
                    .apply {
                        baseConfig()
                    }
            }
            is com.android.build.gradle.internal.plugins.LibraryPlugin -> {
                project.extensions
                    .getByType<com.android.build.gradle.LibraryExtension>()
                    .apply {
                        baseConfig()
                    }
            }
        }
    }
}

But as soon as I move these into gradle/gradle-base-config.gradle.kts, it will no longer compile. I'm assuming because it has no reference to what it is etc, but I can't find anything anywhere on how to expose this. This also happens for configurations should as jacoco configurations when using apply(from = "${projectDir}/gradle/jacoco.gradle.kts there's unresolved references in the kts file, but moving it directly into my app build.gradle everything compiles.

CodePudding user response:

This is unfortunately not supported by kotlin dsl as described here: type safe accessors.

However you can use precompiled script plugins to achieve similar behavior

  • Related