参考多方文档-提供最佳的实践方案(为什么是它)
如果你采用的是 方案二(即在 commonMain
中直接用 implementation("io.realm.kotlin:library-base")
),但又想在 jsMain
中完全禁止 Realm 的使用,你需要处理两个层面的问题:
🚫 问题概述
commonMain
中使用 implementation("io.realm.kotlin:library-base")
,意味着 所有平台(包括 JS)都会尝试解析该依赖。
但是 Realm Kotlin 不支持 JS 平台(只支持 JVM 和 Native),所以会导致:
- 编译错误:JS 无法找到 Realm 的实现运行错误:JS 没有该库的支持,即使编译通过也会运行崩溃
✅ 最佳做法(禁止 JS 平台使用 Realm)
🔧 1. 使用 expect/actual
分离平台实现(推荐方式)
这是官方推荐的 KMP 设计方式 —— 接口放在 commonMain
,平台实现放在 Android/iOS,JS 中不提供实现。
sourceSets { val commonMain by getting { dependencies { // 这样做jsMain还是会参与编译(正确的做法是注销掉,保持个平台持有(否则在编译时就会报错⚠️)) compileOnly("io.realm.kotlin:library-base:1.16.0") } } val androidMain by getting { dependencies { implementation("io.realm.kotlin:library-sync:1.16.0") } } val iosMain by getting { dependencies { implementation("io.realm.kotlin:library-base:1.16.0") } }}
那么问题来了(怎么设计统一调度呢????)
✅ 结构:
interface LocalResponse { var id: String var idToken: String var refreshToken: String var expiresIn: String var localId: String var email: String}expect fun createLocalResponse(): LocalResponseinterface LocalRealm { suspend fun addUser(user: LocalResponse) suspend fun deleteUserById(id: String) suspend fun updateUserEmail(id: String, newEmail: String) suspend fun getAllUsers(): List<LocalResponse> suspend fun getUserById(id: String): LocalResponse? suspend fun getUsersByName(email: String): List<LocalResponse>}expect fun createRealmManager(): LocalRealm
统一调度(直接使用:createLocalResponse ,createRealmManager) …………(^-^)
📌 这样 Realm 的依赖只存在于 android/ios 的
implementation
中,JS 不需要引入 Realm,安全且清晰。
❌ 2. 无法用编译选项跳过 JS 的 Realm 引入
如果你使用的是方案二,在 commonMain
直接使用 implementation("io.realm.kotlin:library-base")
,那么 Gradle 会强制所有平台都解析这个依赖 —— 无法通过 jsMain
禁用。
🚫 方案二无法实现你要的目标
目标 | 方案二能实现吗? |
---|---|
JS 完全排除 Realm(不加载、不编译、不打包) | ❌ 无法做到 |
Realm 仅存在于 Android / iOS 平台 | ❌ 不可能完全排除 |
JS 编译时和运行时都会报错 不兼容 | ⚠️ 高风险 |
✅ 正确做法总结
推荐做法 | 说明 |
---|---|
expect/actual 模式 | JS 平台避免依赖 Realm,同时为其他平台提供实际实现 |
仅在 androidMain/iosMain 引入 Realm | 避免 commonMain 的 implementation("realm") |
JS 提供空实现或报错实现 | 提示用户 JS 不支持 Realm 的操作 |
🔚 结论:
为了在 jsMain
中完全禁止 Realm 的使用,你必须避免在 commonMain
中使用 implementation
引入 Realm。👉 请改用 方案一(平台分离 + expect/actual)实现你的目标。
- Realm 的平台实现JS 抛出异常实现(可选,根据Js支持部署和定义)构建配置结构整理