Build shadow JAR for Gradle plugin with Kotlin and Kotlin DSL.
Posted on:November 12, 2022 (6 min read)
Shadow plugin
Shadow Gradle plugin can help you pack all your project dependencies into a single jar file. It also can help you if you need to use your jar file in some runtime, e.g., as a Spark job or Gradle plugin. In case when your jar dependency conflicts with the dependencies provided by the runtime you can use the Package Relocation to modify byte code and change the package names and related import statements. E.g., the com.fasterxml.jackson package can become relocated.com.fasterxml.jackson and both original and relocated versions will be loaded by the JVM.
The Official documentation has examples for Java and Groovy for Gradle settings.
Let’s find out how we can use it with Kotlin and Kotlin DSL for Gradle plugin packaging.
Use Kotlin DSL
After a brief search, I found an example in the Ktlint Gradle plugin. Let’s take a look at the code.
First, we add new Gradle shadowImplementation configuration. compileOnly and testImplementation will automatically include all the dependencies from the newly created configuration:
Next, configure the relocateShadowJar and shadowJar tasks to automatically relocate all the dependencies from the shadowImplementation configuration:
Since we don’t need the original jar file anymore let’s disable the jar task:
Also ktlint plugin has optional part to check if all the dependencies are inlined into the shadow jar:
Finally, we need to fix the publication settings to publish the shadow jar: