构建.渐变模板



有人知道在创建模块时对build.gradle文件进行模板化的方法吗?现在我遇到的问题是,我希望模块的build.gradle只包含少量信息,因为我将在顶级build.grade文件中设置共享配置。我有一个buildSrc文件夹设置来集中版本控制。

顶级build.gradle文件:

// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath Deps.tools_gradleandroid
classpath Deps.tools_kotlin
classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:1.7.10'
}
}
subprojects {
afterEvaluate { project ->
if (project.hasProperty('android')) {
android {
buildToolsVersion Config.buildTools
compileSdkVersion Config.compileSdk
defaultConfig {
minSdkVersion Config.minSdk
targetSdkVersion Config.targetSdk
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility Config.javaVersion
targetCompatibility Config.javaVersion
}
kotlinOptions {
jvmTarget = Config.javaVersion.toString()
}
}
}
}
}

模块的预期build.gradle文件:

plugins {
id 'com.android.application'
id 'org.jetbrains.kotlin.android'
}
android {
defaultConfig {
applicationId "com.company.expectedmodule"
}
}
dependencies {
implementation Deps.androidx_core
implementation Deps.androidx_appcompat
implementation Deps.androidx_material
testImplementation Deps.testlib_junit
androidTestImplementation Deps.testandroidx_junit
androidTestImplementation Deps.testandroidx_espressocore
}

当我创建一个"新模块"时,build.gradle文件是什么样子的:

plugins {
id 'com.android.application'
id 'org.jetbrains.kotlin.android'
}
android {
compileSdk 32
defaultConfig {
applicationId "com.company.newmodule"
minSdk 21
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
}
dependencies {
implementation 'androidx.core:core-ktx:1.7.0'
implementation 'androidx.appcompat:appcompat:1.5.0'
implementation 'com.google.android.material:material:1.6.1'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}

编辑:为了简单起见,我将依赖项括号移到了顶级build.gradle文件中,还将模块改为库,并将库模块的代码简化为以下代码:

plugins {
id 'com.android.library'
id 'org.jetbrains.kotlin.android'
}
android {
}

建议在Gradle中共享构建逻辑的方法是使用约定插件。就像这个例子一样。

此外,预编译的脚本插件可以用于编写语法类似于常规构建脚本的插件。

最新更新