12
8

More than 1 year has passed since last update.

新しくモジュールを作ったときにbuild.gradleを3行で済まし、カスタマイズをDSLで行う1

Last updated at Posted at 2022-01-23

:warning: この記事の方法はモチベーションや仕組みの話としては問題ありませんが、カスタマイズの部分がうまく動かないので、以下を参考にしてください。 :warning:

これはGradleのプロジェクト全般で利用できると思います。

AndroidやKotlin Multiplatformの開発でたくさんモジュール作って開発していると、毎回build.gradleをレビューしたりとか大変ですよね?

例えばAndroidだと以下のような長い定型文を書く必要があります。

plugins {
    id("com.android.library")
    id("org.jetbrains.kotlin.android")
}

android {
    compileSdk = 32

    defaultConfig {
        minSdk = 21
        targetSdk = 32

        testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
        consumerProguardFiles("consumer-rules.pro")
    }
...
// ながい。。

build.gradle.ktsやbuild.gradleでは以下だけ書けばよくしたいですよね?

plugins {
    id("my.custom.library")
}

あと例えばあるモジュールではJetpack Composeというライブラリが必要とか、カスタマイズが必要なときはDSLで設定すればいいだけにしたいですよね

plugins {
    id("my.custom.library")
}

myCustomExtension {
    useCompose.set(true)
}

この記事ではPrecompiled script pluginsによる方法を紹介します。

といってもすごく簡単です。

Precompiled script pluginsによる実装方法

ここにコードはおいてあります。

buildSrc/build.gradle.kts
plugins {
    `kotlin-dsl`
}
repositories {
    google()
    mavenCentral()
    gradlePluginPortal()
}

// rootのclassspassで書いていたものをここに書く
dependencies {
    implementation("com.android.tools.build:gradle:7.1.0-rc01")
    implementation("com.android.tools.build:gradle-api:7.1.0-rc01")
    implementation("org.jetbrains.kotlin:kotlin-gradle-plugin:1.5.31")
    testImplementation("junit:junit:4.13")
}
buildSrc/src/main/kotlin/my.custom.library.gradle.kts

// プラグインを普通に適応
plugins {
    id("com.android.library")
    id("org.jetbrains.kotlin.android")
}

// カスタマイズしたいもののextensionを書く
abstract class MyCustomPluginExtension {
    abstract val useCompose: Property<Boolean>

    init {
        useCompose.convention(false)
    }
}

// extensionを使えるようにする
val extension = project.extensions.create<MyCustomPluginExtension>("myCustomExtension")

// 普通にAndroidのブロックを書く
android {
    compileSdk = 32

    defaultConfig {
        minSdk = 21
...
    }
    kotlinOptions {
        jvmTarget = "1.8"
    }
    buildFeatures {
        // extensionの値を使う
        compose = extension.useCompose.get()
    }
}

dependencies {
    implementation("androidx.core:core-ktx:1.7.0")
    implementation("androidx.appcompat:appcompat:1.3.0")
    implementation("com.google.android.material:material:1.4.0")
...
}

基本的には書きたいものをbuildSrcの下にファイル名を気をつけて置くだけでした。特殊な記法などを使う必要がなく、思ったよりかんたんでした。

そこまでこの仕組みに詳しくはないのでなにかツッコミどころなどありましたら教えて下さい :pray:

12
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
8