How to use Kotlin CLI – kotlin, kotlinc, kotlinc-js, kotlin-dce-js


I write how to use Kotlin CLI, in Kotlin 1.2.41.

Execute Script

Execute script file with kts extension. If the extension is not kts, the command doesn’t execute anything. The error error: source entry is not a Kotlin file is shown.

sample.kts can be executed if it has no main function.

Sample Code

Compile the File

JVM Compilationル

The following command compiles the Kotlin file with extension kt and generates .class file.

SampleKt.class will be created.

The following command creates JAR file.

There are 2 ways to execute output Sample.jar file, as follows.

JAR execution 1
JAR execution 2

JS Compilation

The following command generates the JavaScript file, sample.js. Map file and meta file are output if you add options.

Kotlin DCE JS

DCE means dead code elimination. It eliminate unused codes in JavaScript. (Reference: https://kotlinlang.org/docs/reference/javascript-dce.html)

For example, create Hello.kt as follows, which has an unused function a.

Compile it as follows.

Then, hello.js will be output.

Then, execute kotlin-dce-js as follows.

You can use -d option to designate the output directory. Here I don’t use it. Without the option, it outputs hello.js into min directory.

The unused function a is successfully deleted.

REPL (Read Eval Print Loop)

We can execute REPL as follows.

To exit the REPL, enter :quit or Ctrl+D.

Help

Execute kotlin, kotlinc, kotlinc-js, kotlin-dce-js commands with the option -h, you can see the help of each command.