2017-01-22 61 views
8

正如标题所示,我想知道如何修改gradle.build.kts以便创建一个具有所有依赖项(包括kotlin lib)的独特jar的任务。如何使用gradle kotlin脚本创建胖罐

我发现这个样品在Groovy:

//create a single Jar with all dependencies 
task fatJar(type: Jar) { 
    manifest { 
     attributes 'Implementation-Title': 'Gradle Jar File Example', 
      'Implementation-Version': version, 
      'Main-Class': 'com.mkyong.DateUtils' 
    } 
    baseName = project.name + '-all' 
    from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } } 
    with jar 
} 

但我不知道我怎么会写在科特林,除了:

task("fatJar") { 

} 

回答

4

您可以使用ShadowJar plugin建立一个胖jar:

import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar 

buildscript { 
    repositories { 
     mavenCentral() 
     gradleScriptKotlin() 
    } 
    dependencies { 
     classpath(kotlinModule("gradle-plugin")) 
     classpath("com.github.jengelman.gradle.plugins:shadow:1.2.3") 
    } 
} 

apply { 
    plugin("kotlin") 
    plugin("com.github.johnrengelman.shadow") 
} 

repositories { 
    mavenCentral() 
} 

val shadowJar: ShadowJar by tasks 
shadowJar.apply { 
    manifest.attributes.apply { 
     put("Implementation-Title", "Gradle Jar File Example") 
     put("Implementation-Version" version) 
     put("Main-Class", "com.mkyong.DateUtils") 
    } 

    baseName = project.name + "-all" 
} 

只需使用'shadowJar'运行任务即可。

注意:这里假定您使用的是GSK 0.7.0(最新截至2017年2月13日)。

+0

不工作,在第一行'进口com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar','ShadowJar'是悬而未决.. – elect

+0

你试过我的回答以来?我有它测试和工作。我认为最初的问题是()需要扩展类。 – mbStavola

+0

我再次尝试了[现在](http://imgur.com/qUozPd2),在'tasks'上面写着'[DELEGATE_SPECIAL_FUNCTION_MISSING]'TaskValue(Build_gradle,KProperty <*>)''类型为'TaskContainer! '' – elect

6

这是一个不使用插件的版本,更像Groovy版本。

import org.gradle.jvm.tasks.Jar 

val fatJar = task("fatJar", type = Jar::class) { 
    baseName = "${project.name}-fat" 
    manifest { 
     attributes["Implementation-Title"] = "Gradle Jar File Example" 
     attributes["Implementation-Version"] = version 
     attributes["Main-Class"] = "com.mkyong.DateUtils" 
    } 
    from(configurations.runtime.map({ if (it.isDirectory) it else zipTree(it) })) 
    with(tasks["jar"] as CopySpec) 
} 

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

Also explained here

+3

这实际上工作 – s1m0nw1

+1

他不是在开玩笑。这应该添加在https://github.com/gradle/kotlin-dsl/tree/master/samples某处 –