I'm looking for a resource which explains how I ca...
# multiplatform
a
I'm looking for a resource which explains how I can reference JavaScript from a Kotlin/JS target inside of a Kotlin/JVM target. For example, I have a Ktor server in Kotlin/JVM and I want to serve scripts like this:
Copy code
routing {
    static("scripts") {
        ... // Serve JavaScript files from this endpoint
    }
}
But instead of just writing JavaScript, I'd prefer to write Kotlin which is then compiled to JavaScript, and serve those generated files. I found the full-stack tutorial in the docs, but the server is written in JavaScript and serves a full React application. I am serving a mostly-static webapp with a little bit of JavaScript.
j
I don't have a tutorial, but I do that with https://github.com/JakeWharton/PosterBox/ if you want to take a look at the build scripts and such
a
Thank you! I think this is not quite what I'm looking for. I did figure out how to get the JS served by the backend, but I essentially have this:
Copy code
head {
            script(type = ScriptType.textJavaScript, src = "/static/scripts/adamcooper-sh.js") {}
}
which does download the script successfully, so that's good. But I am unsure how to load functions from the script.
Copy code
button(classes = "fa fa-copy wordleCopyButton") {
    onClick = 
"copyToClipboard(document.getElementById('$solutionID'));"
}
The
copyToClipboard
function comes from my compiled JS. It throws a
ReferenceError
because it can't find the reference.
j
And you're writing this using kotlinx.html on the backend? There won't be a way to safely reference the functions. You have to export them from your JS and then reference them as strings but you still need a module to load. Otherwise you'd have to expose them on
globalThis
so they're available as top-level functions like you've written there.
I would recommend giving the button an ID and then having the main function of your JS do an ID-based lookup and attach the click listener itself
a
That's a much more reasonable approach. That's me, a backend engineer, trying to write front end :D