Consuming Kotlin through compiled JavaScript

Possibly the easiest way to start consuming our transpiled JavaScript is to load that JavaScript with a <script> tag within an HTML document. In doing this, we can run our main() function when the script is loaded and examine the output in the developer console.

To demonstrate this, let's walk through the following steps:

  1. Add a new index.html file under the root directory, as in the following code snippet:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>HelloKotlinJS</title>
</head>
<body bgcolor="#E6E6FA">
<!-- will load our JavaScript here -->
</body>
</html>

By adding this file, we give ourselves an entry point from which to load and run our JavaScript. If you then open this index.html file in your browser, you should see an empty page with a colored background. We will be updating this shortly.

  1. Within the <body> tag, add two <script> tags, one for kotlin.js and one for ch13.js:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>HelloKotlinJS</title>
</head>
<body bgcolor="#E6E6FA">
<script type="text/javascript"
src="out/production/ch14/lib/kotlin.js"></script>
<script type="text/javascript"
src="out/production/ch14/ch14.js"></script>
</body>
</html>

By adding these <script> tags, we will load the Kotlin standard library and our module's JavaScript code. Note the order of these scripts. It's important that kotlin.js is loaded first because ch14.js relies on the Kotlin standard library. If ch14.js is loaded first, you'll receive an uncaught error when loading your script.

  1. Next, we'll save our index.html file, and then use IntelliJ to open index.html in Google Chrome. With index.html open, you should see several icons representing available web browsers that can be used to view the HTML page, as shown in the following screenshot:

Opening this into our browser will enable us to examine the results of running our JavaScript. Once index.html is open, you should see an empty web page.

  1. To view the results of our JavaScript within Google Chrome, navigate to View | Developer | Developer Tools | Console:

This will allow us to view any console output from our web page. Once the Developer Tools pane has opened, reload your web page and you should then see "Hello Kotlin JavaScript" printed out to the console. This is the result of running our main() function that has been transpiled into ch14.js.

With that, we've completed the journey of creating a new Kotlin project, writing a simple Hello World function in Kotlin, and then consuming that code as JavaScript within a simple web page. While this is a very basic example, it covers the primary workflow of targeting JavaScript with Kotlin. 

In the next section, we'll explore more about how to integrate Kotlin code with other JavaScript, and we'll build on our example to use Kotlin to actually manipulate the content of our web page.