Skip to content

全平台 Gradle 配置

CMP 项目的 build.gradle.kts 比普通 Android 项目复杂,因为它需要定义多个 Target (构建目标) 和 SourceSet (源码集)。

1. 插件配置

在项目的根目录或模块的 build.gradle.kts 中:

kotlin
plugins {
    // Kotlin Multiplatform 核心插件
    kotlin("multiplatform") version "2.0.0"
    // Compose Multiplatform 插件
    id("org.jetbrains.compose") version "1.6.10"
    // Compose 编译器 (Kotlin 2.0+ 内置,旧版需单独配置)
    id("org.jetbrains.kotlin.plugin.compose") version "2.0.0"
    // Android 库或应用插件
    id("com.android.application")
}

2. Target 定义

这是配置的核心,决定了你的代码可以运行在哪些平台上。

kotlin
kotlin {
    // 1. Android Target
    androidTarget {
        compilations.all {
            kotlinOptions { jvmTarget = "1.8" }
        }
    }

    // 2. Desktop Target (JVM)
    jvm("desktop")

    // 3. iOS Targets
    // 通常需要配置全部架构以支持模拟器和真机
    listOf(
        iosX64(),
        iosArm64(),
        iosSimulatorArm64()
    ).forEach { iosTarget ->
        iosTarget.binaries.framework {
            baseName = "ComposeApp"
            isStatic = true
        }
    }

    // 4. Web Target (Wasm)
    @OptIn(ExperimentalWasmDsl::class)
    wasmJs {
        moduleName = "composeApp"
        browser {
            commonWebpackConfig {
                outputFileName = "composeApp.js"
            }
        }
        binaries.executable()
    }
}

3. 依赖管理 (SourceSets)

CMP 遵循分层架构:commonMain 是所有平台共享的,平台特定的 SourceSet 可以依赖特定库。

kotlin
kotlin {
    sourceSets {
        // --- 核心共享层 ---
        val commonMain by getting {
            dependencies {
                // 引入 Compose 基础库
                implementation(compose.runtime)
                implementation(compose.foundation)
                implementation(compose.material3)
                implementation(compose.ui)
                // 资源库 (1.6.0+)
                implementation(compose.components.resources)
            }
        }

        // --- Android 层 ---
        val androidMain by getting {
            dependencies {
                implementation("androidx.activity:activity-compose:1.9.0")
                implementation("androidx.appcompat:appcompat:1.6.1")
                // 可以使用所有 Android 原生库 (如 CameraX, Retrofit)
            }
        }

        // --- Desktop (JVM) 层 ---
        val desktopMain by getting {
            dependencies {
                implementation(compose.desktop.currentOs) // 包含当前系统的 Skiko 引擎
                implementation("org.jetbrains.kotlinx:kotlinx-coroutines-swing:1.8.0")
            }
        }

        // --- iOS 层 ---
        val iosMain by getting {
            dependencies {
                // 通常不需要额外依赖,直接调用 Apple SDK
            }
        }
    }
}

4. Android 配置块

Android 仍然需要标准的 android { } 配置块。

kotlin
android {
    namespace = "com.example.project"
    compileSdk = 34

    defaultConfig {
        minSdk = 24
        targetSdk = 34
    }
    // ...
}