As discussed previously in this chapter, when we build a Kotlin project that is targeting JavaScript, the compiler will transpile our Kotlin code into human-readable JavaScript for use in whatever web application we may be building. This includes the Kotlin standard library as well. The results of this compilation process can be seen in our output directory after a project build. The following screenshot depicts this:
As mentioned in the last section, we have four outputs from the compilation of our current Hello World project:
- lib/kotlin.js
- lib/kotlin.meta.js
- ch14.js
- ch14.meta/js
Notice the pattern with these outputs? We have ch14.js and lib/kotlin.js, as well as two examples of <file>.meta.js that correspond to the other two output files. For each module in our project, the compiler will create a <module>.js file. In our example, that is ch14.js.
At the project level, the compiler must generate JavaScript for the Kotlin standard library, which is output as kotlin.js. This kotlin.js file should be the same for any project using the same version of Kotlin.
For each transpiled .js file, the compiler also then generates a corresponding <file>.meta.js, which is used primarily for reflection. These files are generally of less concern to us as they are not generally human-readable. However, the .js files generated for the Kotlin standard library and each of our modules is designed to be human-readable, so we can understand what the transpiled JavaScript is doing.
If we open up ch14.js, we can see the JavaScript code equivalent of our Hello World Kotlin example, as shown here:
if (typeof kotlin === 'undefined') {
throw new Error("Error loading module 'ch14'. The dependency 'kotlin'
was not found. Please, check whether 'kotlin' is
loaded prior to 'ch14'.");
}
var ch14 = function (_, Kotlin) {
'use strict';
var println = Kotlin.kotlin.io.println_s8jyv4$;
function main() {
var outputMessage = 'Hello Kotlin JavaScript';
println(outputMessage);
}
_.main = main;
main();
Kotlin.defineModule('ch14', _);
return _;
}(typeof ch14 === 'undefined' ? {} : ch14, kotlin);
This JavaScript is the result of the compiler transpiling the Kotlin standard library, our own code, and then ensuring that all of the dependencies are still met. The result of this JavaScript is a variable assigned the result of a self-executing, anonymous function call. When that function is declared, it is executed, which, in turn, executes the transpiled version of our main() function from main.kt. In this case, this results in our "Hello Kotlin JavaScript" message being printed out to the console.
Now that we've seen how our Kotlin has been transpiled into usable JavaScript, let's look at how we can actually start consuming this code.