Posted on

kotlin_4_js_page5

Main.kt

package okoko
import kotlin.browser.document
import kotlin.browser.window
external fun jQuery(selector: dynamic): dynamic = definedExternally

fun log() {
    println("log from Kotlin for JavaScript!")
}

fun jtext(selector:dynamic,txt:dynamic) {
    jQuery(selector).text(txt)
}

fun boombayah() {
    jQuery(document).ready({
        jQuery("p").click( { jtext("p","Thank You, Sir!") })
        jtext("p","If you click on me, You will be mesmerized.")
    })
}

fun main(args: Array<String>) {
    println("Welcome to Kotlin for JavaScript!")
    boombayah()
}

build.gradle

buildscript {
    ext {
        kotlin_version = "1.3.11"
    }
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version")
    }
}

apply plugin: "kotlin2js"
apply plugin: "kotlin-dce-js"

repositories {
    mavenCentral()
}

dependencies {
    compile("org.jetbrains.kotlin:kotlin-stdlib-js:$kotlin_version")
}

defaultTasks "ko4js"
assemble.dependsOn runDceKotlinJs

build.doLast {
    configurations.compile.each { File file ->
        copy {
            includeEmptyDirs = false

            from zipTree(file.absolutePath)
            into "${projectDir}/js"
            include { fileTreeElement ->
                def path = fileTreeElement.path
                path.endsWith(".js") && (path.startsWith("META-INF/resources/") || !path.startsWith("META-INF/"))
            }
        }
    }
}

task uglifyjs(type: Exec) {
    commandLine "uglifyjs", "build/kotlin-js-min/main/kotlin.js", "build/kotlin-js-min/main/ko4js.js", "-c","-m", "-o", "js/ko4js.core.js"
}

task ko4js {
    dependsOn build, uglifyjs, runDceKotlinJs
    uglifyjs.mustRunAfter runDceKotlinJs
}

compileKotlin2Js {
    kotlinOptions.outputFile = "${projectDir}/js/ko4js.js"
    kotlinOptions.moduleKind = "plain"
    kotlinOptions.sourceMap = false
    kotlinOptions.sourceMapEmbedSources = "never"
    kotlinOptions.metaInfo = false
}

task wrapper(type: Wrapper,overwrite: true) {
    gradleVersion = "5.0"
    distributionType = Wrapper.DistributionType.ALL
}

Main.kt becomes ko4js.js after gradle build

if (typeof kotlin === 'undefined') {
  throw new Error("Error loading module 'ko4js'. Its dependency 'kotlin' was not found. Please, check whether 'kotlin' is loaded prior to 'ko4js'.");
}
var ko4js = function (_, Kotlin) {
  'use strict';
  var println = Kotlin.kotlin.io.println_s8jyv4$;
  var Unit = Kotlin.kotlin.Unit;
  function log() {
    println('log from Kotlin for JavaScript!');
  }
  function jtext(selector, txt) {
    jQuery(selector).text(txt);
  }
  function boombayah$lambda$lambda() {
    jtext('p', 'Thank You, Sir!');
    return Unit;
  }
  function boombayah$lambda() {
    jQuery('p').click(boombayah$lambda$lambda);
    jtext('p', 'If you click on me, you will be mesmerized.');
    return Unit;
  }
  function boombayah() {
    jQuery(document).ready(boombayah$lambda);
  }
  function main(args) {
    println('Welcome to Kotlin for JavaScript!');
    boombayah();
  }
  var package$okoko = _.okoko || (_.okoko = {});
  package$okoko.log = log;
  package$okoko.jtext_wn2jw4$ = jtext;
  package$okoko.boombayah = boombayah;
  package$okoko.main_kand9s$ = main;
  main([]);
  Kotlin.defineModule('ko4js', _);
  return _;
}(typeof ko4js === 'undefined' ? {} : ko4js, kotlin);

Now uglifyjs combines ko4js.js with kotlin.js and minify the result to produce ko4js.core.js.

The final ko4js.core.js is ~50KB. Not bad size when considering it is a transpiled JavaScript from Kotlin and jquery.min.js is ~80KB.

ex4.html

<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cloud.ibinti.com/file/ko4js/ko4js.core.js"></script>
</head>
<body>

<p>If you click on me, you will be blessed.</p>

</body>
</html>
Posted on

kotlin_4_js_page4

package okoko
import kotlin.browser.document
import kotlin.browser.window
external fun jQuery(selector: Any?): Unit

fun log() {
    println("log from Kotlin for JavaScript!")
}

fun jtext(selector:Any,txt:Any) {
    jQuery(selector).asDynamic().text(txt)
}

fun boombayah() {
    jQuery(document).asDynamic().ready({
        jQuery("p").asDynamic().click( { jtext("p","Thank You, Sir!") })
        jtext("p","If you click on me, You will be mesmerized.")
    })
}

fun main(args: Array<String>) {
    println("Welcome to Kotlin for JavaScript!")
}
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cloud.ibinti.com/file/ko4js/ko4js.core.js"></script>
<script>ko4js.okoko.boombayah()</script>
</head>
<body>

<p>If you click on me, You will be blessed.</p>

</body>
</html>
Posted on

kotlin_4_js_page2

Gradle

build.gradle

buildscript {
    ext {
        kotlin_version = "1.3.11"
    }
    repositories {
        mavenCentral()
    }

    dependencies {
        classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version")
    }
}

apply plugin: "kotlin2js"

repositories {
    mavenCentral()
}

dependencies {
    compile("org.jetbrains.kotlin:kotlin-stdlib-js:$kotlin_version")
}

defaultTasks "ko4js"

build.doLast {
    configurations.compile.each { File file ->
        copy {
            includeEmptyDirs = false

            from zipTree(file.absolutePath)
            into "${projectDir}/js"
            include { fileTreeElement ->
                def path = fileTreeElement.path
                path.endsWith(".js") && (path.startsWith("META-INF/resources/") || !path.startsWith("META-INF/"))
            }
        }
    }
}

task uglifyjs(type: Exec) {
    commandLine "uglifyjs", "js/kotlin.js", "js/kotlinx-coroutines-core-js.js", "js/kotlinx-html-js.js", "js/ko4js.js", "-b", "-o", "js/ko4js.core.js"
}

task ko4js {
    dependsOn build, uglifyjs
    uglifyjs.mustRunAfter build
}

compileKotlin2Js {
    kotlinOptions.outputFile = "${projectDir}/js/ko4js.js"
    kotlinOptions.moduleKind = "plain"
    kotlinOptions.sourceMap = false
    kotlinOptions.sourceMapEmbedSources = "never"
    kotlinOptions.metaInfo = false
}

task wrapper(type: Wrapper,overwrite: true) {
    gradleVersion = "5.0"
    distributionType = Wrapper.DistributionType.ALL
}
Posted on

kotlin_4_js_page1

Unified coding model. Kotlin is an interesting programming language that can write codes for both web front-end JavaScript and back-end server side JavaScript as well as server Java Virtual Machine (JVM). Kotlin also does native Android and iOS apps. Kotlin can work things out with existing JavaScript and JVM ecosystems and native C/Objective-C/C++/Swift static, dynamic libraries and frameworks.

In this article, I would like to teach myself on how to target JavaScript with Kotlin.

Official Kotlin documents on the Web: here

Official document recommends to use Gradle build tool. So I will use Gradle to generate JavaScript code from Kotlin code.

Also I would like to use jQuery as an example of existing JavaScript library.

Here is a sample HTML with JavaScript

<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("p").click(function(){
    $(this).text("Bless You!");
  });
});
</script>
</head>
<body>

<p>If you click on me, You will be blessed.</p>

</body>
</html>

The JavaScript part of the example above is:

$(document).ready(function(){
  $("p").click(function(){
    $(this).text("Bless You!");
  });
});

I will produce above JavaScript code with Kotlin. Follow me next.