Ralph Bergmann
Ralph Bergmann

Reputation: 3076

How do I export a Kotlin JS project?

Sorry, but the Kotlin documentation doesn't help me to export a Kotlin JS project to deploy it on my webserver.

I created a new Kotlin Browser Application with the new project wizard in IntelliJ.

build.gradle.kts:

plugins {
    kotlin("js") version "1.4.21"
}

group = "com.foo"
version = "1.0-SNAPSHOT"

repositories {
    jcenter()
    mavenCentral()
}

kotlin {
    js(LEGACY) {
        browser {
            binaries.executable()
        }
    }
}

simple.kt:

class APIModule {
    fun greet() = "world"
}

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JS Client</title>
</head>
<body>
<script src="untitled.js"></script>
<script>
    let module = new untitled.APIModule()
    console.info(`greet: ${module.greet()}`)
</script>


<div id="root"></div>
hallo ralph
</body>
</html>

When I call ./gradlew clean browserRun, it opens a new browser window, and on the JavaScript console, I see the expected (index):11 greet: world.

The question now is: What is the right Gradle task to export it. I tried ./gradlew clean browserWebpack, but when I now open the generated HTML file, I get an index.html:10 Uncaught TypeError: untitled.APIModule is not a constructor at index.html:10 error.

Upvotes: 3

Views: 1802

Answers (1)

Travis
Travis

Reputation: 2026

When using IR compiler with @JsExport you can call Kotlin functions from JavaScript.

build.gradle.kts

kotlin {
    js(IR) {
        browser()
        binaries.executable()
    }
}

example.kt (in untitled project module)

@JsExport
fun hello() { console.info("hi") }

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JS Client</title>
</head>
<body>
<script src="untitled.js"></script>
<script>
    untitled.hello(); // prints "hi" to console.
</script>


<div id="root"></div>
hallo ralph
</body>
</html>

Run ./gradlew browserDistribution then open build/distributions/index.html.


When using LEGACY compiler, I've only been able to invoke Kotlin from JavaScript (for static generated pages) when running the browserDevelopmentWebpack Gradle task. 😢

Upvotes: 3

Related Questions