如何创建依赖于 Kotlin 项目中的 JS 的 Gradle 项目?

How do I create a Gradle project that depends on the JS from a Kotlin project?

我正在使用 Kotlin 在后端(Java Spring Web)和前端之间共享逻辑。让 Java 后端调用 Kotlin 逻辑很容易:我将两个部分都设为相同的 Gradle 多项目构建,并让服务器项目依赖于 Kotlin 项目。

现在我需要从 Kotlin 中获取生成的 Java 脚本,并将其转换为服务器可以提供的格式。查看服务器的 Gradle 输出 jar,它只有 jvm jar 而没有 js jar。

我在 this GitHub project 中遇到了类似的问题,有一个 Spring 引导后端和一个 Kotlin/JS 前端 + 公共代码。

如果所有内容都在多个 Gradle 子项目的同一个 repo 中,您可以在服务器子项目中使用以下内容将生成的 JS 作为资源捆绑到服务器的 jar 中:

tasks.processResources {
    // make sure we build the frontend before creating the jar
    dependsOn(":frontend:assemble")
    // package the frontend app within the jar as static
    val frontendBuildDir = project(":frontend").buildDir
    val frontendDist = frontendBuildDir.toPath().resolve("distributions")
    from(frontendDist) {
        include("**/*")
        into("static")
    }
}

它并不理想(我不喜欢这样的项目间依赖关系),但它可以完成工作。

Spring 启动然后自动从 jar (/static) 中的这个位置提供静态文件。