Kotlin to WebAssembly

WebAssembly (WASM) is poised to be the next major disruptive technology. In the past, JavaScript was the only predominant viable option for executing code within browsers. With WebAssembly, you can compile code written in many different languages—including C, C++, Rust, Go, C#, Python, Java, and Kotlin—to the WASM binary instruction format, for a stack-based virtual machine that runs within modern browsers. WASM brings many benefits, including speed of development using higher-level languages, high runtime performance, enhanced safety, and code that’s easier to test and debug and that interoperates with code written in different languages.

Kotlin to WebAssembly is currently in initial stages at the time of this writing. Treat the material in this appendix as experimental.

To target Kotlin to WASM, use the Kotlin/Native compiler with the -target wasm32 command-line option. If you’ve not had a chance to install the Kotlin/Native distribution in Kotlin/Native, do so before you continue.

Setting up Node.js application

In this appendix, we’ll create a small example to draw on an HTML5 canvas, using Kotlin code to illustrate Kotlin to WASM targeting. We’ll need an HTML file to fire up a page in the browser. We’ll also need Kotlin source code to draw on the canvas that will be defined within the HTML file. In addition to using Kotlin/Native, we also need a minimal lightweight web server to serve the files into a browser. Let’s get these things set up, one step at a time.

In an empty directory named wasm, run the command npm init and accept the defaults—for this step you’ll need to have Node.js installed on your system. When done, install the lite-server using the command npm install lite-server --save.

After the installation completes, open the file package.json and edit it to add a start command to start the lite-server. The file should look like the following when you’re done with these steps—the version of lite-server that you see may be different.

// package.json
{
  "name": "wasm",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "lite-server"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "lite-server": "^2.4.0"
  }
}

Create an index.html file with the following content:

Get hands-on with 1400+ tech skills courses.