0

I'd like to write some of my code in Kotlin such that it can be used by both a JVM-based backend and a JS-based frontend.

To do the former (with the new IR complier), the classes have to be annotated with @JsExport. However, if I then try to use build the same file for a JVM, it breaks because that annotation is not recognized.

(These are separate projects with independent gradle configs but linking to the same Kotlin source tree. It's not a single "multiplatform" build.)

How can I export Kotlin/JS while still being compatible with Kotlin/Java?

Brian White
  • 8,332
  • 2
  • 43
  • 67

1 Answers1

0

To achieve that seperation and reusability, you need three gradle submodules that would depend on each other

  1. The 'shared' module. The one with the common code
  2. The 'backend' module. Purely kotlin/jvm module
  3. The 'frontend' module. A purely kotlin/js module

Your gradle project structure should look something like this

project-root
  - shared
    - src/commonMain/kotlin
    - build.gradle.kts
  - backend
    - src/main/kotlin
    - build.gradle.kts
  - frontend
    - src/main/kotlin
    - build.gradle.kts
  - settings.gradle.kts

shared/build.gradle.kts should look like this

plugins {
  kotlin("multiplatform")
}

and then backend/build.gradle.kts

plugins {
  kotlin("jvm")
}

kotlin {
  sourceSets {
     val main by getting {
         dependencies {
             implementation(projects(":shared"))
         }
     }

  }
}

and then backend/build.gradle.kts

plugins {
  kotlin("js")
}

kotlin {
  sourceSets {
     val main by getting {
         dependencies {
             implementation(projects(":shared"))
         }
     }

  }
}

and then settings.gradle.kts

include(":shared",":backend",":frontend")

With this sort of arrangement, You can write your shared code inside shared/src/commonMain/kotlin and environment specific code on their respective backend or frontend submodules

NOTE: The gradle configs above have been minimised to narrow down the explanation

andylamax
  • 1,858
  • 1
  • 14
  • 31