Search code examples
androidgradlegradle-kotlin-dsl

can we use gradle.kts for files other than build.gradle.kts


I have a custom publish file written in groovy publish.gradle, and I wanted to migrate this to publish.gradle.kts file, issue seems apply plugins don't work in the any file other than build.gradle.kts, for example

publish.gradle.kts

apply(plugin ="maven-publish")
apply(plugin ="com.jfrog.artifactory")
artifactory{ .....
....

I cannot access to artifactory method in this file even after adding jfrog plugin, is this possible and I'm missing something?


Solution

  • The way to do it in Kotlin is to write a pre-compiled script plugin.

    A Kotlin script needs a bit more setup because it is statically typed – the compiler needs to know what types are available at compile time.

    The easiest way to set this up is to use the buildSrc folder:

    1. Write your script in a file eg publish.gradle.kts in buildSrc/src/main/kotlin

    2. Add a build.gradle.kts file in the buildSrc folder (yes, the script itself needs building) and place the following in as a minimum:

      plugins {
          `kotlin-dsl`
      }
      

      The Kotlin DSL plugin looks for Kotlin script plugins and places them on the build classpath. Any other types your script needs (including external plugin JARs) need to be provided here.

    3. Now you can apply your plugin in the main project build files:

      plugins {
          publish
      }