Search code examples
kotlin-multiplatformkotlin-js

Problem while converting code to new IR JS Compiler


I have a simple Kotlin Multiplatform Library project that works great with Legacy JS compiler, here's a simple class code :

package net.mggk.kwl

import kotlin.js.JsName

class CustomFunc {
    @JsName("sayHello")
    fun sayHello() {
        println("Hello from kotlin library :D")
    }
    @JsName("multiplyPerTwo")
    fun multiplyPerTwo(x: Int): Int {
        return 2 * x
    }
}

And my gradle configuration for JS :

js(LEGACY) {
    nodejs()
}

I'm currently trying to migrate to the new IR compiler, i've read the migration guide and updated my gradle configuration to this :

js(IR) {
    nodejs{}
    binaries.executable()
}

And my class to this :

package net.mggk.kwl

import kotlin.js.JsExport

@kotlin.js.ExperimentalJsExport
@JsExport
class CustomFunc {
    fun sayHello() {
        println("Hello from kotlin library :D")
    }
    fun multiplyPerTwo(x: Int): Int {
        return 2 * x
    }
}

But, with this new config, no JS file is outputed by the compiler, the package.json file is present but no JS file.

If anyone have an idea about how to fix this, i'm currently lookig to write cross-platform libraries with kotlin, but not manage to compile a simple class is a dead end for me.

Thanks for your feedback.


Solution

  • Steps to create a project and getting correct JS output

    Tool: IntelliJ IDEA 2021.3.2

    • Create a new project (Gradle based + Kotlin/Multiplatform + Kotlin DSL Build script)
    • Once initial setup is loaded, add js target in build.gradle.kts
    kotlin {
        js(IR) {
            nodejs()
            binaries.executable()
        }
        // ........
    }
    
    • Add jsMain source set
    sourceSets {
        // .....
        val jsMain by getting
    }
    
    • Add src/jsMain/kotlin folder under root
    • Add a file with any name. For example Temp.kt
    • Copy-paste above code from question
    • To go terminal and run gradle command to generate JS lib
    ./gradlew jsNodeProductionRun
    
    • Go to build/js/packages/<YourLibName>/kotlin/

    Open <YourLibName>.js file and see the generate JS code

    You'll find JS code for class in the question

      function CustomFunc() {
      }
      CustomFunc.prototype.sayHello = function () {
        println('Hello from kotlin library :D');
      };
      CustomFunc.prototype.multiplyPerTwo = function (x) {
        return imul(2, x);
      };
      CustomFunc.$metadata$ = {
        simpleName: 'CustomFunc',
        kind: 'class',
        interfaces: []
      };