LoginSignup
0
1

マルチモジュールでの依存関係の記述をいい感じにする

Posted at

マルチモジュール

マルチモジュールは、どんどん肥大化するプロジェクトにおいて効率性を維持するためにおすすめの方法です。アプリケーションを独立したモジュールに分割することで

  • ビルドの高速化
  • よいアーキテクチャを強制できる

というメリットがあります。

一方で、モジュールの数が増えると、各モジュールでそれぞれ依存関係を管理するのは大変です。バージョンカタログを導入することによって、マルチモジュールでの依存関係を簡単に管理できるようになります。

バージョンカタログ

バージョンカタログは依存ライブラリとプラグインのバージョンを一元管理するためのGradleの機能です。

バージョンカタログファイルを作成

ルートのgradleフォルダにlibs.versions.tomlファイルを作成します。Gradleはデフォルトでこのファイル名を読み込むので、ファイルを作成するだけで大丈夫です。

libs.version.toml
[versions]

[libraries]

[plugins]

ライブラリの場合

バージョンカタログファイルのversionslibrariesに追加します。ライブラリに追加する名前はケバブケース(androidx-core-ktxなど)にします。こうするとbuild.gradle.ktsではdotに置き換えた形で参照できます(libs.androidx.core.ktx)

変更前

build.gradle.kts
dependencies {
    implementation("androidx.core:core-ktx:1.12.0")
}

変更後

libs.versions.toml
[versions]
core-ktx = "1.12.0"

[libraries]
androidx-core-ktx = { group = "androidx.core", name="core-ktx", version.ref = "core-ktx" }

build.gradle.kts
dependencies {
    implementation(libs.androidx.core.ktx)
}

プラグインの場合

変更前

Top-level build.gradle.kts
plugins {
    id("com.android.application") version "8.2.2" apply false
}
Module-level build.gradle.kts
plugins {
    id("com.android.application")
}

変更後

libs.versions.toml
[versions]
androidGradlePlugin = "8.2.2"

[plugins]
android-application = { id = "com.android.application", version.ref = "androidGradlePlugin" }
Top-level build.gradle.kts
plugins {
    alias(libs.plugins.android.application) apply false
}
Module-level build.gradle.kts
plugins {
    alias(libs.plugins.android.application)
}

バージョンの設定

バージョン名をそのまま使うパターンも同様です。

変更前

build.gradke.kts
android {
    composeOptions {
        kotlinCompilerExtensionVersion = "1.5.7"
    }
}

変更後

libs.versions.toml
[versions]
androidxComposeCompiler = "1.5.7"
build.gradle.kts
android {
    composeOptions {
        kotlinCompilerExtensionVersion = libs.versions.androidxComposeCompiler.get().toString()
    }
}

プロジェクト間の依存

Gradle 7.0で試験的に導入されたTYPESAFE_PROJECT_ACCESSORS機能を使うと、プロジェクトの依存もバージョンカタログと同じように、文字列ではなく型安全に参照できます。

変更前

build.gralde.kts
dependencies {
    implementation(project(":core:data"))
}

変更後

settings.gradle
enableFeaturePreview("TYPESAFE_PROJECT_ACCESSORS")
build.gralde.kts
dependencies {
    implementation(projects.core.data)
}

参考

0
1
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
0
1