Compiling Kotlin/JS into a .js Library for Including in Static HTML

Recently, I’m trying to get a hang of using Kotlin/JS by doing some little experiments. Before going too deep like writing code for solving daily use-cases, I’ve decided to stick to the “Hello World”-ish tradition, trying to write a library that could log a message and could be used (imported and called) independently

Here is what I have done, main.kt, within the module named KotlinJSTest

@JsName("writeToConsole")
fun writeToConsole() {
    console.log("Testing")
}

A simple library that will log a message on the console.

After that, I run the task build using this Gradle script build.gradle.kts

plugins {
    id("org.jetbrains.kotlin.js") version "1.4.21"
}
group = "org.example"
version = "1.0-SNAPSHOT"
repositories {
    mavenCentral()
}
dependencies {
    implementation(kotlin("stdlib-js"))
}
kotlin {
    js {
        browser {
        }
        binaries.executable()
    }
}

What I am expecting is a single KotlinJSTest.js that I could simply use in some static HTML, like

...
<body>
    <script src = "./kotlin.js"></script>
    <script src = "./KotlinJSTest.js"></script>
    <script>
        KotlinJSTest.writeToConsole();
    </script>
</body>
...

AFAIK, I also need an extra kotlin.js for the library to work, right?
So I have been searching for KotlinJSTest.js and kotlin.js inside the build folder. However, what I have found is 3 KotlinJSTest.js and 2 kotlin.js, and two of the KotlinJSTest.js even doesn’t have the function declaration for writeToConsole()!

With KotlinJSTest.js from build/js/packages/KotlinJSTest/kotlin/ and kotlin.js from build/js/packages_imported/kotlin/1.4.21/ (and their corresponding .js.map) it finally works, after I have tried most of the combinations.

So, what I am asking is, is there anyway, like messing with settings or options in build.gradle.kts, that could let those two (truly) “necessary” .js files to be output in the same folder, instead of having me going back and forth to find them? And is there even a way that could reduce these files into just ONE, SINGLE .js file, instead of two .js and their corresponding .js.map? I have already spent half of the day just on this question. Most of the articles do not take me anywhere, so please help me if you have some time to spare, thank you in advance.

Oh, and this is the little project that I’ve mentioned. (the HTML is not included

1 Like