Gradle自动化构建项目

概览:

安装Gradle

  • getting-started

  • 需要 Java运行时环境(JRE)或Java Development Kit(JDK),版本1.8或更高版本(仅运行Gradle时需要)

  • A Gradle distribution, version 4.10.3 or better (将Gradle的bin添加到环境变量)

初始化

先打开项目目录(gradle_test为例),选择默认选项。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
$ gradle init
Starting a Gradle Daemon, 1 incompatible Daemon could not be reused, use --status for details

Select type of project to generate:
1: basic
2: application
3: library
4: Gradle plugin
Enter selection (default: basic) [1..4]

Select build script DSL:
1: Groovy
2: Kotlin
Enter selection (default: Groovy) [1..2]

Project name (default: gradle_test):


> Task :init
Get more help with your project: https://guides.gradle.org/creating-new-gradle-builds

BUILD SUCCESSFUL in 36s
2 actionable tasks: 2 executed
  • 目录树
1
2
3
4
5
6
7
8
├── build.gradle  
├── gradle
│ └── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
└── settings.gradle

构建示例

压缩打包

新建src/myfile.txt,并写入以下内容。

1
2
this is source file.
wait for zip.

编辑build.gradle,并写入以下内容。

1
2
3
4
5
6
7
8
plugins {
id "base"
}

task zip(type: Zip, group: "Archive", description: "Archives sources in a zip file") {
from "src"
setArchiveName "basic-demo-1.0.zip"
}

Gradle包含一系列插件,Gradle插件门户网站上提供了许多插件。该发行版附带的base插件是插件之一。结合所调用的核心类型Zip,您可以使用配置的名称和位置创建项目的zip存档。

执行task

1
./gradlew zip # task name

这是可能会下载Downloading https://services.gradle.org/distributions/gradle-5.5.1-bin.zip

如果你已经下载过。

可以将压缩包复制到本项目gradle/wrapper目录下。像这样,并修改gradle-wrapper.properties,将distributionUrl指向本地的gradle-5.5.1-bin.zip.

1
distributionUrl=gradle-5.5.1-bin.zip

然后继续执行

1
2
3
4
5
6
$ ./gradlew zip
Downloading file:/E:/SublimeText3/gradle_test/gradle/wrapper/gradle-5.5.1-bin.zip
.....................................................................................

BUILD SUCCESSFUL in 18s
1 actionable task: 1 executed

task结果

会在项目根目录build/distributions产生叫basic-demo-1.0.zip的压缩包.

解压查看即使src目录下的文件。