使用 Gradle Kotlin DSL 包含脚本

Include scripts with Gradle Kotlin DSL

我正尝试在项目中使用 gradle 的 Kotlin DSL,但有以下限制:

Groovy我们有什么:

结果(仅基于我的示例):

我试图用 Gralde KTS 重现同样的东西,但遇到了以下困难:

包含文件示例:

apply plugin: 'kotlin'

compileKotlin {
    kotlinOptions {
        jvmTarget = "1.8"
    }
}

compileTestKotlin {
    kotlinOptions {
        jvmTarget = "1.8"
    }
}

Gradle 模块示例:

apply from: "${rootDir}/gradle/include/kotlin-common-include.gradle"

dependencies {
    compile project(':my.project.libraries.common') 

    compile group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: springBootVersion
}

问题:

附加链接:

Kotlin DSL 当前 (5.3) 存在限制,无法在任何地方进行编译时检查。为了让 Kotlin DSL 工作,它必须在 Gradle API 之上添加扩展,但它不能神奇地做到这一点。首先,您需要浏览 Kotlin DSL Primer 页面才能理解它。

How can I extract plugin applying to the include scripts (to avoid Gradle module scripts overload)?

一种方法是将 precompiled build scripts 与 Kotlin DSL 插件一起使用。为此,您需要将脚本移动到 $rootDir/buildSrc 项目中。它可能是这样的:

// $rootDir/buildSrc/build.gradle.kts
plugins {
  `kotlin-dsl`
}
repositories {
   maven {
     url = uri("http://host:8082/artifactory/...")
  }
}

然后把你的常用脚本写成这样:

// $rootDir/buildSrc/src/main/kotlin/common.gradle.kts
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile

plugins {
  kotlin("jvm") version "1.3.21"
}
tasks.compileKotlin {
  kotlinOptions.jvmTarget = "1.8"
}
tasks.compileTestKotlin {
  kotlinOptions.jvmTarget = "1.8"
}

然后你可以将这个脚本应用到这样的插件上:

// $rootDir/build.gradle.kts
subprojects {
  apply(id = "common")
}

How can I use precompiled script plugins without public global repositories access?

为预编译脚本插件配置自定义存储库与您通常的构建脚本没有什么不同。这样做:

// $rootDir/buildSrc/settings.gradle.kts
pluginManagement {
  repositories.maven {
    url = uri("http://host:8082/artifactory/...")
  }
}

如果您不想使用预编译插件,另一种方法是显式配置扩展。你可以这样做:

// $rootDir/gradle/common.gradle.kts
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
tasks.withType<KotlinCompile> {
  kotlinOptions.jvmTarget = "1.8"
}

在主脚本中:

// $rootDir/build.gradle.kts
subprojects {
  apply {
    plugin(KotlinPlatformJvmPlugin::class)
    from("common.gradle.kts")
  }
}

How can I put all common constants (such as dependency versions) to the separate file to include them just by using something like springBootVersion or Constants.springBootVersion with compile-time checks?

目前没有好的方法。您可以使用额外的属性,但它不能保证编译时检查。类似的东西:

// $rootDir/dependencies.gradle.kts

// this will try to take configuration from existing ones
val compile by configurations
val api by configurations
dependencies {
  compile("commons-io:commons-io:1.2.3")
  api("some.dep")
}

// This will put your version into extra extension
extra["springBootVersion"] = "1.2.3"

你可以这样使用它:

// $rootDir/build.gradle.kts
subprojects {
  apply {
    plugin<JavaLibraryPlugin>()
    from("$rootDir/dependencies.gradle.kts")
  }

在你的模块中:

// $rootDir/module/build.gradle.kts
// This will take existing dependency from extra
val springBootVersion: String by extra
dependencies {
  compile("org.spring:boot:$springBootVersion")
}