kotlingradlekotlin-multiplatformgradle-multi-project-build

How do I create a Gradle project that depends on the JS from a Kotlin project?


I am using Kotlin to share logic between my back end (Java Spring Web) and front end. Getting the Java back end to call the Kotlin logic is easy: I made both part of the same Gradle Multiproject build and have the server project depend on the Kotlin project.

Now I need to get the generated JavaScript out of Kotlin and into a format where the server can serve it. Looking through the Gradle output jar for the server, it only has the jvm jar and not the js jar.


Solution

  • I had a similar problem in this GitHub project with a Spring Boot backend and a Kotlin/JS frontend + common code.

    If everything is in the same repo in multiple Gradle subprojects, you can use the following in the server subproject to bundle the produced JS as resources into your server's jar:

    tasks.processResources {
        // make sure we build the frontend before creating the jar
        dependsOn(":frontend:assemble")
        // package the frontend app within the jar as static
        val frontendBuildDir = project(":frontend").buildDir
        val frontendDist = frontendBuildDir.toPath().resolve("distributions")
        from(frontendDist) {
            include("**/*")
            into("static")
        }
    }
    

    It's not ideal (I don't like inter-project dependencies like this), but it does the job.

    Spring Boot then automatically serves the static files from this place in the jar (/static).