Fat Jar 使用 Gradle Kotlin DSL 扩展依赖项

Fat Jar expands dependencies with Gradle Kotlin DSL

我正在尝试在基于 Kotlin 的 gradle 文件中使用以下内容构建一个 fat jar。

val fatJar = task("fatJar", type = Jar::class) {
  baseName = "safescape-lib-${project.name}"
  // manifest Main-Class attribute is optional.
  // (Used only to provide default main class for executable jar)
  from(configurations.runtimeClasspath.map({ if (it.isDirectory) it else zipTree(it) }))
  with(tasks["jar"] as CopySpec)
}

tasks {
  "build" {
    dependsOn(fatJar)
  }
}

但是,fat jar 扩展了所有依赖项。我想将 jars 包含在 /lib 目录中,但我不知道如何实现这一点。

任何人都可以指导我如何实现这一目标吗?

谢谢

您在规范的 map 部分使用了 zipTree,它的行为符合 the documentation:它解压缩不是目录的文件。

如果您想要 /lib 中的罐子,请将 from 替换为:

from(configurations.runtimeClasspath) {
    into("lib")
}

万一有人在使用 kotlin-multiplatform 插件,配置会有点不同。这是一个 fatJar 任务配置,假设 JVM 应用程序具有来自 JS 模块的嵌入式 JS 前端:

afterEvaluate {
  tasks {
    create("jar", Jar::class).apply {
      dependsOn("jvmMainClasses", "jsJar")
      group = "jar"
      manifest {
        attributes(
          mapOf(
            "Implementation-Title" to rootProject.name,
            "Implementation-Version" to rootProject.version,
            "Timestamp" to System.currentTimeMillis(),
            "Main-Class" to mainClassName
          )
        )
      }
      val dependencies = configurations["jvmRuntimeClasspath"].filter { it.name.endsWith(".jar") } +
          project.tasks["jvmJar"].outputs.files +
          project.tasks["jsJar"].outputs.files
      dependencies.forEach { from(zipTree(it)) }
      into("/lib")
    }
  }
}