clay
clay

Reputation: 20390

Gradle Project: Copy Dependencies to Build Directory

How do I copy my project's dependencies to the build directory?

This is a very common question. I've searched and found many threads that answer this exact question, but none of the solutions are working. Here are three threads (some are quite old) that give solutions that I am unable to get working.

Gradle equivalent to Maven's "copy-dependencies"?

How to Copy dependencies to Build directory in Gradle

https://discuss.gradle.org/t/how-can-i-gather-all-my-projects-dependencies-into-a-folder/7146

FYI, I've tried, among others:

task copyDependencies(type: Copy) {
   from configurations.compile
   into 'dependencies'
}

task copyDependencies2(type: Copy) {
    from project.configurations.compile
    into project.buildDir
}

project.copy {
    from project.configurations.compile
    into project.buildDir
}

If possible, I prefer current recommended best practices methods rather than older deprecated methods. I'm staying on the current Gradle, which is currently 4.7 as of this writing.

Upvotes: 1

Views: 5984

Answers (3)

Anthony Puitiza
Anthony Puitiza

Reputation: 111

I spent a lot of time trying to fix that. This works on Gradle 7.4.1

task copyAllDependencies(type: Copy) {
  from configurations.compileClasspath
  into "${buildDir}/output/libs"
}
build.dependsOn(copyAllDependencies)

enter image description here

Upvotes: 2

Mike Clark
Mike Clark

Reputation: 10136

It is recommended to use the built-in "distribution" plugin.

plugins {
    id 'distribution'
}

group 'org.yourorg'
version '1.0-SNAPSHOT'

repositories {
    mavenCentral()
}

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.12'
    compile group: 'log4j', name: 'log4j', version: '1.2.17'
}

distributions {
    main {
        contents {
            from jar // copies your jar
            from(project.configurations.runtime) // copies dependency jars
        }
    }
}

Then you can run one command which will compile and assemble in a single step:

gradlew installDist

This creates the distribution as a directory structure under ./build/install/
Furthermore, you can create the distribution as a zip under ./build/distributions/

gradlew distZip

If you want to separate the built jar from the dependencies, this is conventional:

distributions {
    main {
        contents {
            from jar
            into('lib') {
                from(project.configurations.runtime)
            }
        }
    }
}

Upvotes: 1

clay
clay

Reputation: 20390

OK, after playing with this for several hours, I have a solution that works. This is very different from older solutions which don't seem to work on current versions of Gradle. This one works on Gradle 4.7:

task jarWithDeps(dependsOn: 'jar', type: Copy) {
  def conf = configurations.runtimeClasspath
  from conf.allDependencies.collect { conf.files(it) }
  into "${project.buildDir}/libs"
}

Upvotes: 5

Related Questions