【问题标题】:How do I export a Kotlin JS project?如何导出 Kotlin JS 项目?
【发布时间】:2021-01-12 16:50:01
【问题描述】:

抱歉,Kotlin 文档无法帮助我导出 Kotlin JS 项目以将其部署到我的网络服务器上。

我使用 IntelliJ 中的新项目向导创建了一个新的 Kotlin 浏览器应用程序。

build.gradle.kts:

plugins {
    kotlin("js") version "1.4.21"
}

group = "com.foo"
version = "1.0-SNAPSHOT"

repositories {
    jcenter()
    mavenCentral()
}

kotlin {
    js(LEGACY) {
        browser {
            binaries.executable()
        }
    }
}

simple.kt:

class APIModule {
    fun greet() = "world"
}

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JS Client</title>
</head>
<body>
<script src="untitled.js"></script>
<script>
    let module = new untitled.APIModule()
    console.info(`greet: ${module.greet()}`)
</script>


<div id="root"></div>
hallo ralph
</body>
</html>

当我调用 ./gradlew clean browserRun 时,它会打开一个新的浏览器窗口,在 JavaScript 控制台上,我会看到预期的 (index):11 greet: world

现在的问题是:导出它的正确 Gradle 任务是什么。我尝试了./gradlew clean browserWebpack,但是当我现在打开生成的 HTML 文件时,我收到了一个index.html:10 Uncaught TypeError: untitled.APIModule is not a constructor at index.html:10 错误。

【问题讨论】:

    标签: kotlin-js


    【解决方案1】:

    将 IR 编译器与 @JsExport 一起使用时,您可以从 JavaScript 调用 Kotlin 函数。

    build.gradle.kts

    kotlin {
        js(IR) {
            browser()
            binaries.executable()
        }
    }
    

    example.kt (在untitled项目模块中)

    @JsExport
    fun hello() { console.info("hi") }
    

    index.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>JS Client</title>
    </head>
    <body>
    <script src="untitled.js"></script>
    <script>
        untitled.hello(); // prints "hi" to console.
    </script>
    
    
    <div id="root"></div>
    hallo ralph
    </body>
    </html>
    

    运行./gradlew browserDistribution,然后打开build/distributions/index.html


    使用LEGACY 编译器时,我只能在运行browserDevelopmentWebpack Gradle 任务时从JavaScript 调用Kotlin(用于静态生成的页面)。 ?

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-18
    • 2020-07-02
    • 1970-01-01
    • 2017-04-27
    • 2018-02-17
    • 1970-01-01
    相关资源
    最近更新 更多