我试图了解在 Gradle、Kotlin DSL 中应用插件的所有方式。 This question 回答了我的问题的一部分,但不是全部(我猜方法是在它们之后的六年中添加的)。
我在我的一个 build.gradle.kts
文件中看到了这种确切的场景。
plugins{
`kotlin-dsl`
kotlin("jvm") version "1.6.10"
id("com.foo.bar.someplugin") version 1.2.3
}
apply("foo2.bar2.anotherplugin")
哇,这是应用插件的四种不同方式,我完全不明白它们之间的关系。从另一个答案中,我知道 apply(...)
是传统方式,最终会被弃用,但是其他三个呢?
此外,我对为什么 `kotlin-dsl`
甚至不需要版本感到困惑。这是什么巫术魔法?
最后,为了保持一致性,我想标准化 plugins block (让我们忽略 apply(...)
因为它是遗留功能),以便所有内容都使用 id (...)
。如何转换另外两个?
最佳答案
实际上,您已经确定了主要只有 2 种方法:构建脚本依赖项 + apply
和 plugins
block 。您的插件 block 中的内容实际上只是助手:
id("some.plugin.id") version "version"
是用ID和版本注册插件的基本方式kotlin()
实际上只是 Kotlin DSL 提供的一个辅助函数,它通过org.jetbrains.kotlin 在后台调用
前缀在您传递的任何字符串之前。所以id()
。kotlin("jvm")
只是id("org.jetbrains.kotlin.jvm")
的简写
kotlin-dsl
也是一个辅助函数,它是 Kotlin DSL Gradle 插件的快捷方式。我相信字符串 ID 是org.gradle.kotlin.kotlin-dsl
。
在应用插件的传统方式中,您必须在 buildscript
block 中声明对插件的依赖关系,以便将插件的类添加到类路径中以编译/执行 Gradle脚本本身。第二步,调用 apply
实际上会将插件应用到当前项目。
使用 plugins
block ,两者同时发生,因此使用起来更方便。您还可以在插件声明之后添加 apply false
以便将其添加到类路径中而无需将其应用到项目中:
plugins {
id("com.foo.bar.someplugin") version 1.2.3 apply false
}
如果您想在根项目中声明所有插件及其版本,然后使用不带版本的 plugins
block 将相关的插件应用到子项目中,这将非常有用:
plugins {
id("com.foo.bar.someplugin")
}
Furthermore, I'm confused by why the
kotlin-dsl
doesn't even need a version. What is this voodoo magic?
从上面的解释可以看出,任何已经在类路径中的插件都不需要版本。这适用于已在父项目或 settings.gradle(.kts)
的 plugins
中声明的插件,以及内置的 Gradle 插件。
Kotlin DSL 插件是一个内置的 Gradle 插件,因此它使用的版本取决于您使用的 Gradle 版本。它类似于 java
或 application
插件。
还明确建议避免为其指定版本in the doc :
Avoid specifying a version for the kotlin-dsl plugin. Each Gradle release is meant to be used with a specific version of the kotlin-dsl plugin and compatibility between arbitrary Gradle releases and kotlin-dsl plugin versions is not guaranteed. Using an unexpected version of the kotlin-dsl plugin in a build will emit a warning and can cause hard to diagnose problems.
现在关于你的另一个问题:
I would like to standardize the plugins block (let's ignore the apply(...) since it's legacy functionality) so that everything uses id(...). How do I convert the other two?
这里的写法非常地道,所以这应该被认为是“标准”。这实际上是建议在文档中使用的方式。使用 kotlin-dsl
是区分内置 Gradle 插件和第三方插件的好方法。此外,它是一种类型安全的插件声明方式,IDE 可以理解,您可以搜索引用等。字符串在这方面稍逊一筹。
如果你真的想用基于字符串的语法来应用它,你可能会使用 id("org.gradle.kotlin.kotlin-dsl")
,但我从未见过到目前为止,有一个项目可以做到这一点。
kotlin()
帮助器可能更值得商榷,而且是个人喜好问题,但 IMO 越少任意字符串越好。
关于kotlin - 了解在 Gradle 中应用插件的所有方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70394598/