通过开发 Settings 文件学习编写 Gradle 构建的基础知识。
步骤 1. Gradle 脚本
Build 脚本和 settings 文件都是代码。它们使用 Kotlin 或 Groovy 编写。
你可以使用 Kotlin DSL、Groovy DSL 和 Gradle API 来编写脚本。
在 Gradle 脚本中主要可以使用以下方法
-
Gradle API - 例如来自 Settings API 的
getRootProject()
方法 -
在 DSL 中定义的块 - 例如来自 KotlinSettingsScript 的
plugins{}
块 -
插件定义的扩展 - 例如应用
java
插件时提供的implementation()
和api()
方法
步骤 2. Settings
对象
settings 文件是每个 Gradle 构建的入口点。
在初始化阶段,Gradle 会在项目根目录中查找 settings 文件。
当 settings 文件 settings.gradle(.kts)
被找到时,Gradle 会实例化一个 Settings 对象。
Settings 对象的一个目的是允许你声明构建中要包含的所有项目。
你可以直接在 settings 文件中使用 Settings 接口上的任何方法和属性。
例如
includeBuild("some-build") // Delegates to Settings.includeBuild()
reportsDir = findProject("/myInternalProject") // Delegates to Settings.findProject()
includeBuild('some-build') // Delegates to Settings.includeBuild()
reportsDir = findProject('/myInternalProject') // Delegates to Settings.findProject()
步骤 3. Settings 文件
让我们分解一下项目根目录中的 settings 文件
settings.gradle.kts
plugins { (1)
id("org.gradle.toolchains.foojay-resolver-convention") version "0.10.0" (2)
}
rootProject.name = "authoring-tutorial" (3)
include("app") (4)
include("lib")
includeBuild("gradle/license-plugin") (5)
1 | 来自 PluginDependenciesSpec API 的 plugins({}) 方法 |
2 | 来自 PluginDependenciesSpec API 的 id() 方法 |
3 | 来自 Settings API 的 getRootProject() 方法 |
4 | 来自 Settings API 的 include() 方法 |
5 | 来自 Settings API 的 includeBuild() 方法 |
settings.gradle
plugins { (1)
id 'org.gradle.toolchains.foojay-resolver-convention' version '0.10.0' (2)
}
rootProject.name = 'running-tutorial-groovy' (3)
include('app') (4)
include('lib')
includeBuild('gradle/license-plugin') (5)
1 | 来自 Kotlin DSL 中 KotlinSettingsScript 的 plugins({}) 方法 |
2 | 来自 PluginDependenciesSpec API 的 id() 方法 |
3 | 来自 Settings API 的 getRootProject() 方法 |
4 | 来自 Settings API 的 include() 方法 |
5 | 来自 Settings API 的 includeBuild() 方法 |
下一步: 编写 Build 脚本 >>