Android:在单独的 kotlin dsl 脚本中添加 maven-publish 配置

Mah*_*alv 4 android gradle maven-publish gradle-kotlin-dsl

我编写了一个.gradle名为 的脚本publish.gradle,用于配置publishing {}发布我的工件。

为什么要写一个单独的脚本?我有多个模块,通过这样做,每个可发布的模块只需定义一些变量。

模块build.gradle.kts

// Module's blah blah

apply(from = "../publish.gradle")
Run Code Online (Sandbox Code Playgroud)

publish.gradle

apply plugin: 'maven-publish'



publishing {
   publications {
      // configure release process
   }
}
  
Run Code Online (Sandbox Code Playgroud)

我最近决定迁移到Gradle Kotlin DSL。然而,有一个问题:

publication {}像这样添加:

apply plugin: 'maven-publish'



publishing {
   publications {
      // configure release process
   }
}
  
Run Code Online (Sandbox Code Playgroud)

导致这个错误:

Expression 'publishing' cannot be invoked as a function. The function 'invoke()' is not found
Unresolved reference. None of the following candidates is applicable because of receiver type mismatch:
public val PluginDependenciesSpec.publishing: PluginDependencySpec defined in org.gradle.kotlin.ds
Run Code Online (Sandbox Code Playgroud)

总结为

PluginDependencySpec 不作为接收器存在

有什么不同?

TL; DR

我已将publishing {}配置添加到一个单独的脚本中,该脚本在 groovy 格式下可以工作.gradle,但无法转换为.gradle.ktskotlin 格式。这是脚本中不存在的类publishing的扩展。PluginDependenciesSpec

Tom*_*hik 5

这对我有用:

plugins {
    id("maven-publish")
}

configure<PublishingExtension> {
    publications.create<MavenPublication>("myPlugin") {
        groupId = "com.myCompany.android"
        artifactId = "MyPlugin"
        version = "1.0.0"
        pom.packaging = "jar"
        artifact("$buildDir/libs/MyPlugin.jar")

    }
    repositories {
        mavenLocal()
   }
}
Run Code Online (Sandbox Code Playgroud)

我明白你的出发点,从 groovy 脚本转换为 kotlin 脚本并不是简单的一对一翻译,我们大多数人,包括我自己,都是通过示例编写代码。换句话说,你只需要看一个简单的例子,剩下的你就可以明白了。当示例很容易获得时,这非常有效。当你找不到示例时,你需要做的就是查阅 API 文档。例如,https://docs.gradle.org/current/dsl/org.gradle.api.publish.PublishingExtension.html向您显示 PublishingExtension 的可用属性,您可以继续深入查看您在下一级。当示例可能使用旧版本并且可能不再适用时,这一点尤其重要。我想说的是,不太明显的是,要访问 kotlin 脚本中的扩展,需要配置块。这是一个很大的区别,但我喜欢这种方法,因为它使扩展属性的组成部分更加清晰。顺便说一下,kotlin 想要双引号,单引号不再被接受。