Transpiling to JavaScript

Front-end development is gaining momentum, and there’s an increasing demand for full-stack developers. JavaScript has evolved significantly in recent years, but it’s a dynamically typed language and also a weakly typed language—–see Rediscovering JavaScriptVenkat Subramaniam. Rediscovering JavaScript. The Pragmatic Bookshelf, Raleigh, NC, 2018. In recent years, some programmers have gravitated toward statically typed languages, for example TypeScript, that will transpile to JavaScript. Statically typed languages can help find errors early, during compile time, and remove certain problems that may creep up during runtime if the code was written directly in JavaScript.

Languages like TypeScript offer static typing, but languages like Kotlin bring in that and a lot more. If you’re going to choose static typing for front-end development, why stop at languages like TypeScript, when you could go all the way and benefit from the wealth of features of a powerful language like Kotlin? Kotlin makes it easier to create common code and to reuse code between platforms. You can also use Kotlin DSLs for HTML and CSS and thus use Kotlin for the entire front-end development.

Though the focus of this book isn’t on creating front-end applications with Kotlin, let’s explore this idea of Kotlin to JavaScript a bit here. If you’re using IntelliJ IDEA, it’ll extract the necessary Kotlin JavaScript runtime library for you automatically when you compile to JavaScript. If you’re using other IDEs or a build tool, you have to do some extra steps. Here, you’ll see how to use the command line to compile and run the generated JavaScript code both in Node and within a browser.

Compiling in the command line

We’ll write a Kotlin source file, transpile it to JavaScript, and also extract the necessary Kotlin JavaScript runtime library files from the Kotlin distribution.

Let’s start with a Kotlin file first.

Get hands-on with 1200+ tech skills courses.