How to package library jars except module jar in gradle?

Viewed 84

How to ask gradle to package just the dependency jars in a zip without the module jar that contains the module classes?

I'm using Kotlin Gradle DSL, but Groovy solutions also welcomed. I can translate them to Kotlin myself.

1 Answers

You can set up a Zip task as follows:

tasks.register('packageDeps', Zip) {
    from configurations.runtimeClasspath
}

It depends on the kind of project you have, which configuration you need to copy from. In the example, it’s a Java project and we copy the dependencies from the runtime classpath (i.e., the runtimeClasspath configuration). You can run ./gradlew dependencies to find out which configurations exist in your project; you can only use the ones that are meant to be resolved, i.e., the ones that don’t have an (n) in their description.

Example Project

Here’s a self-contained project that I’ve tested this with (not showing Gradle 7.2 Wrapper files):

├── build.gradle
├── settings.gradle
└── src
    └── main
        └── java
            └── com
                └── example
                    └── MyClass.java

When running ./gradlew packageDeps on that project, the ZIP file build/distributions/my-deps.zip is created which contains only dependency JARs (incl. transitive ones) and not the MyClass.class file or a corresponding JAR.

build.gradle

plugins {
    id 'java'
}

repositories {
    mavenCentral()
}

dependencies {
    implementation 'com.google.guava:guava:28.2-jre'
}

tasks.register('packageDeps', Zip) {
    from configurations.runtimeClasspath
    archiveFileName = 'my-deps.zip'
}

settings.gradle

(empty)

src/main/java/com/example/MyClass.java

package com.example;

public class MyClass {

    public static void main(String... args) {
        System.out.println("Hello world!");
    }
}
Related