Search code examples
reactjsvert.xgradle-kotlin-dslkotlin-multiplatform

How to glue together Vert.x web and Kotlin react using Gradle in Kotlin MPP


Problem

It is not clear to me how to configure the Kotlin MPP (multiplatform platform project) using Gradle (Kotlin DSL) to use Vert.x web for Kotlin/JVM target with Kotlin React on the Kotlin/JS target.

Update

You can check out updated minimal example for a working solution inspired by an approach of Alexey Soshin.

What I've tried

Have a look at my minimal example on GitHub of a Kotlin MPP with the Vert.x web server on the JVM target and Kotlin React on the JS target.

You can make it work if you:

  • First run Gradle task browserDevelopentRun (I don't understand magick behind it) and after browser opens and renders React SPA (single page application) you can
  • stop that task and then
  • start the Vert.x backend with task run.

After that, without refreshing the remaining SPA in the browser, you can confirm that it can communicate with the backend by pressing the button and it will alert received data.

Question

What are the possible ways/approaches to glue these two targets so when I run my application: JS target is assembled and served via JVM backend conveniently?

I am thinking that perhaps Gradle should trigger some of the Kotlin browser tasks and then make them available in some way for the Vert.x backend.


Solution

  • If you'd like to run a single task, though, you need that your server task would depend on your JS compile. In your build.gradle add the following:

    tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile> {
        dependsOn(tasks.getByName<org.jetbrains.kotlin.gradle.targets.js.webpack.KotlinWebpack>("jsBrowserProductionWebpack"))
    }
    

    Now invoking run will also invoke WebPack.

    Next you want to serve your files. There are different ways of doing it. One is to copy them to Vert.x resources directory using Gradle. Another is to point Vert.x to where WebPack puts them by default:

    route().handler(StaticHandler.create("../../../distributions"))