The previous two examples each showed a rather different approach to loading our JavaScript code. UMD tries to combine the best of both worlds: use AMD if it's available, fallback to plain.
In this example we'll even combine them!
First we change the Kotlin compilation options to use umd
:
tasks {
"compileKotlin2Js"(Kotlin2JsCompile::class) {
kotlinOptions {
outputFile = "${project.buildDir.path}/js/ktjs_example03.js"
moduleKind = "umd"
...
}
}
}
Then we need to load the scripts in our HTML. Probably you should use either plain or AMD but here we will load both.
One remark before showing how to load the scripts: The JS generated by Kotlin (our build/js/ktjs_example03.js script!) starts by checking if AMD is available
build/js/ktjs_example03.js
if (typeof define === 'function' && define.amd)
So it's important to first load the plain scripts (when AMD is not yet available) and only afterwards load our module as an AMD module using RequireJS:
umd.html
<!DOCTYPE html>
<html>
<head>
<!-- Important: First the plain scripts -->
<script type="text/javascript" src="./scripts/kotlin.js"></script>
<script type="text/javascript" src="build/js/ktjs_example03.js"></script>
<!-- Important: load this after the plain js (scripts/kotlin.js and build/js/ktsj_example03.js -->
<script data-main="./scripts/main.js" src="./scripts/require.js"></script>
</head>
<body>
...
</body>
</html>
Obviously this is a source of conflicts which I ignore here because it's just a simple example.
The rest is basically just a combination of example 1 and example 2.
For the HTML <script/>
tags we use the plain JS:
umd.html
<div><span>Plain: Access a function in the root: </span><div id="plainfoobar"></div></div>
<script>
document.getElementById("plainfoobar").innerText = ktjs_example03.bar();
</script>
And for the AMD module we use requirejs:
umd.html
<div><span>AMD: Access a function in the root: </span><div id="amdfoobar"></div></div>
<script>
// see scripts/main.js
</script>
scripts/main.js
requirejs.config({
paths: {
kotlin: './kotlin',
ktjs_example03_umd: '../build/js/ktjs_example03'
}
});
requirejs(["ktjs_example03_umd"], function (example03) {
document.getElementById("amdfoobar").innerText = example03.bar();
...
});