How to get Kotlin JS to work with JQuery (or other external libraries)
If you have tried to get external javascript libraries working with Kotlin (when compiling to javascript) it can be somewhat puzzling to get external libraries to work with Kotlin while at the same time being typesafe.
Kotlin provides https://kotlinlang.org/docs/reference/dynamic-type.html to work around this, but this sort of defeats the point of using the static language IMO. A nicer option exists: generate a header for the javascript file that kotlin can apply typechecking to. Here are the steps involved. Github repo for the example is at the bottom of the article.
- curl https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/master/types/jquery/index.d.ts > jquery.d.ts
- install the typescript-to-kotlin converter: npm -g install ts2kt ( https://github.com/Kotlin/ts2kt )
- convert jquery.d.ts to jquery.kt by running ts2kt -d headers jquery.d.ts
- create a new kotlin project and target js for the runtime
- within the src directory in your project, create 2 packages: jslibs and jsheaders
- download jquery.js from https://jquery.com/download/ and place it in jslibs
- move the jquery.kt header file you generated (should be in the headers dir where you ran ts2kt) to jsheaders
- create a new html file within the Kotlin project. the project should have an index.html file at the top level that includes the following:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>kotlinjquerytest</title>
</head>
<body>
<script type="text/javascript" src="out/production/{name of project}/lib/kotlin.jslibs"></script>
<script type="text/javascript" src="out/production/{name_of_project}/jslibs/jquery-3.2.1.min.jslibs"></script>
<script type="text/javascript" src="out/production/{name_of_project}/{name_of_project}.jslibs"></script>
<div id="app" style="width:200px; height: 200px;border:1px solid red;"></div>
</body>
</html>
make sure to change nameofproject to... the name of the project you chose
- create a kotlin file within source called Main.kt with the following:
fun jQuery(x: String) = jQuery(x, null as JQuery?)
fun main(args: Array<String>) {
jQuery {
Main.doApp()
}
}
object Main {
fun doApp() {
val jQuery1 = jQuery("#app")
jQuery1[0]?.innerHTML = "<p>hey!</p>"
}
}
- double click the index.html file
- at the top right, select a browser icon to open the file
- congrats!
Download the example project at: http://github.com/mutexkid/kotlinjquerytest