Introduction to Kotlin (to) JavaScript

综合技术 2018-05-18 阅读原文

Introduction

Kotlin is a JVM language that borrows from Scala in an attempt to improve Java. In contrast to Java and Scala (GWT and Scala.js), in which the to-JavaScript compiler is an independent framework, Kotlin provides a to-JavaScript compiler as an integral part of its compiler. Another difference between Kotlin compiler and other frameworks is that Kotlin provides its lib in a separate file (named kotlin.js ), in addition to the compiled source code. This leads to the neccessity to include both files, or find tools to concatenate them. In this post, we will go through a simple example of setting up and running Kotlin to JavaScript.

Setup

There are different ways to setup Kotlin to JavaScript based on the IDE or the used build tool (more details can be found in the official documentation ). For this tutorial, we are going to choose the Maven way, as this is the build tool we use often. After spining up a simple maven project through IntelliJ, the following dependencies and plugins need to be added:

                
                    org.jetbrains.kotlin
                    kotlin-stdlib-js
                    ${kotlin.version}
                
                
                    org.jetbrains.kotlin
                    kotlin-stdlib
                    ${kotlin.version}
                
            

            
                src/main/kotlin
                
                    
                        org.jetbrains.kotlin
                        kotlin-maven-plugin
                        ${kotlin.version}
                        
                            
                                compile
                                compile
                                
                                    js
                                    compile
                                
                            
                            
                                test-compile
                                test-compile
                                
                                    test-js
                                    test-compile
                                
                            
                        
                    
                    
                        org.apache.maven.plugins
                        maven-dependency-plugin
                        
                            
                                unpack
                                compile
                                
                                    unpack
                                
                                
                                    
                                        
                                            org.jetbrains.kotlin
                                            kotlin-stdlib-js
                                            ${kotlin.version}
                                            ${project.build.directory}/js/lib
                                            *.js
                                        
                                    
                                
                            
                        
                    
                
            

the kotlin-maven-plugin compiles kotlin to byte code through the compile goal and compiles the source code to JavaScript through the js goal. The kotlin-stdlib-js is used by the maven-dependency-plugin for including the kotlin.js file which contains the JavaScript version of Kotlin’s runtime and standard library. kotlin.js is static and does not change from an application to another, so it is possible to copy it manually or to import it directly in the HTML page from a link (e.g a CDN). kotlin.js is tied to the used Kotlin version.

Example :

Let’s print a Hello world to the console and examine the generated JavaScript:

fun main(args: Array) {
    println("Hello World!")
}

Generated kotlinjs-intro.js :

if (typeof kotlin === 'undefined') {
  throw new Error("Error loading module 'kotlinjs-intro'. Its dependency 'kotlin' was not found. 
                   Please, check whether 'kotlin' is loaded prior to 'kotlinjs-intro'.");
}
this['kotlinjs-intro'] = function (_, Kotlin) {
  'use strict';
  var println = Kotlin.kotlin.io.println_s8jyv4$;
  function main(args) {
    println('Hello World!');
  }
  var package$com = _.com || (_.com = {});
  var package$gwidgets = package$com.gwidgets || (package$com.gwidgets = {});
  var package$kotlinjs = package$gwidgets.kotlinjs || (package$gwidgets.kotlinjs = {});
  package$kotlinjs.main_kand9s$ = main;
  main([]);
  Kotlin.defineModule('kotlinjs-intro', _);
  return _;
}(typeof this['kotlinjs-intro'] === 'undefined' ? {} : this['kotlinjs-intro'], kotlin);

As mentionned earlier, the generated script looks for defined Kotlin runtime methods and classes and throws an error if kotlin.js is not already loaded. This may lead to issues if scripts are included in the body or have "defer" attributes because the order is important. One possible solution is to use JavaScript build tools such as Grunt or Gulp to concatenate the two scripts.

Another inconvenience is the size of the scripts. Minifying and optimizing the JavaScript code is important for production settings. While GWT and Scala.js provide the user with the option to minify the generated script or run the Closure compiler for even more optimization, Kotlin leaves this task to the developer.

For this simple example, the total size loaded is about 1.51 MB, which is not ideal compared to GWT or Scala.js or even other JavaScript frameworks (check out this comparison between different front end frameworks). After minifying and concatening both scripts, the result is:

which is is better, but still far behind GWT and Scala.js.

Size of .js for printing a Hello World to the console
GWT59.5 KB (.nocache.js plus the loaded module)
Scala.js11.6 KB
Kotlin to JavaScript1.1 MB

Ecosystem

Kotlin JavaScript seem to have several bindings for popular JavaScript Librairies ( https://github.com/kodando/kodando , https://github.com/JetBrains/kotlin-wrappers , and many others) like react, jquery, and also a dom API, but the ecosystem remains small as Kotlin in itself is a niche and relatively new compared to other JVM languages.

Wrap-up

Kotlin to JavaScript is an interesting tool, but it seems like it is still in its infancy and still has a lot to learn. According to Kotlin’s documentation , Kotlin to JavaScript can be used to target both front-end and server side JavaScript. From a front-end perspective, Scala.js and GWT seem like better options. We will explore the generation of server side JavaScript in coming posts.

G-Widgets

责编内容by:G-Widgets阅读原文】。感谢您的支持!

您可能感兴趣的

通用后台管理系统UI模板-AdminLTE简介及构造动态菜单栏... AdminLTE是一款基于bootstrap的后台管理系统的通用模板UI,它的样式美观且较为符合大多数后台管理系统的需求,典型的上|左右|下的布局形式。并且提供了一整套我们开发的时候可能用到的UI样式,比如表格,表单,图表,日历等。非常适合...
What is this thing called this? The easiest way to describe this is that it refers to the object it's assigned when called . For example, conside...
.class click button i have a div with multiple like buttons and i have the following code where when a user press on one of the like buttons...
JS 中的闭包是什么? 本文为 饥人谷讲师方方 原创文章,首发于 前端学习指南 。 大名鼎鼎的闭包!面试必问。 请用自己的话简述 什么是「闭包」。 「闭包」的作用是什么。 首先来简述什么是闭包 假设上面三行...
Tilt and Zoom Layout on Mouse Motion I was trying to search a few messages in chat when I saw this: With the movement of mouse to left or right, the c...