如何使用正确的名称将 Kotlin 函数导出到 Javascript

How to export Kotlin functions to Javascript with correct name

我正在尝试将 Kotlin 函数导出到 Javascript。问题是,需要参数的函数在 Kotlin2JS 操作后被重命名,这是一个例子:

Kotlin 来源:

fun withParam(args: String) {
    println("JavaScript generated through Kotlin")
}

fun withoutParams() {
    println("Without params")
}

在 Kotlin2JS 之后,尝试在 Node REPL 中要求:

> const kotlinBundle = require('./build/index.js');
undefined
> kotlinBundle
{ 'withParam_61zpoe$': [Function: withParam],
  withoutParams: [Function: withoutParams] }
>

如您所见,带参数的函数以 _61zpoe$ 后缀导出。是否可以去掉那部分?

我正在使用 kotlin2js 插件和 kotlin-stdlib-js:1.1.1 库,我的 kotlinOptions 是:

compileKotlin2Js.kotlinOptions {
  moduleKind = "commonjs"
  outputFile = "build/index.js"
}

谢谢

您可以使用@JsName 注释为已编译的函数(或其他符号)提供准确的名称javascript。 即

@JsName("withParam")    
fun withParam(args: String) {
      println("JavaScript generated through Kotlin")
}