You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin多平台与Gradle:如何将依赖移至单独文件

Kotlin多平台项目依赖拆分可行方案

方案1:Gradle版本目录(官方推荐)

这是Gradle官方主推的依赖管理方式,天然适配Kotlin多平台的依赖处理逻辑,无需纠结接收者类型问题。

  1. 在项目根目录新建gradle/libs.versions.toml文件,集中管理依赖版本与声明:
[versions]
# 统一维护版本号
ktor = "2.2.4"
coroutines = "1.7.3"

[libraries]
# 定义具体依赖,关联对应版本
ktor-server-netty = { module = "io.ktor:ktor-server-netty", version.ref = "ktor" }
ktor-server-core = { module = "io.ktor:ktor-server-core", version.ref = "ktor" }
kotlinx-coroutines-core = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "coroutines" }
  1. 在模块的build.gradle.kts中直接引用:
sourceSets {
    val jvmMain by getting {
        dependencies {
            implementation(libs.ktor.server.netty)
            implementation(libs.ktor.server.core)
        }
    }
    val commonMain by getting {
        dependencies {
            implementation(libs.kotlinx.coroutines.core)
        }
    }
}

Gradle会自动生成类型安全的libs对象,直接点选调用即可,还能避免依赖拼写错误。

方案2:buildSrc中编写KotlinDependencyHandler扩展函数

之前用buildSrc失败是因为扩展了DependencyHandlerScope,改成针对KotlinDependencyHandler写扩展即可:

  1. 在buildSrc/src/main/kotlin下新建DependencyExtensions.kt文件:
import org.jetbrains.kotlin.gradle.dsl.KotlinDependencyHandler

// 封装JVM主源码集的依赖
fun KotlinDependencyHandler.addJvmMainDependencies() {
    implementation("io.ktor:ktor-server-netty:2.2.4")
    implementation("io.ktor:ktor-server-core:2.2.4")
    // 其他JVM主依赖都放在这里
}

// 封装通用主源码集的依赖
fun KotlinDependencyHandler.addCommonMainDependencies() {
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.7.3")
}
  1. 在模块的build.gradle.kts中调用扩展函数:
sourceSets {
    val jvmMain by getting {
        dependencies {
            addJvmMainDependencies()
        }
    }
    val commonMain by getting {
        dependencies {
            addCommonMainDependencies()
        }
    }
}

方案3:抽成独立Gradle脚本导入

不想用buildSrc的话,可以把依赖逻辑单独写成脚本,通过apply from导入使用:

  1. 在项目根目录的gradle文件夹下新建dependencies.gradle.kts文件:
// 定义针对KotlinDependencyHandler的依赖函数
fun KotlinDependencyHandler.jvmMainDeps() {
    implementation("io.ktor:ktor-server-netty:2.2.4")
}

fun KotlinDependencyHandler.commonMainDeps() {
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.7.3")
}
  1. 在模块的build.gradle.kts顶部导入脚本:
apply(from = "../gradle/dependencies.gradle.kts")
  1. 在sourceSets中调用对应函数:
sourceSets {
    val jvmMain by getting {
        dependencies {
            jvmMainDeps()
        }
    }
}

内容的提问来源于stack exchange,提问作者Splitframe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 10:51:19