1

我有一个我喜欢导出的 Kotlin JS 项目,以便它可以在非 Kotlin React 应用程序中使用。

我尝试过的事情(假设模块被称为exportedlib):

  1. 将其导出为 CommonJS 模块,使用gradlew compileKotlinJs.

然后我复制build/js/packages/exportedlib/kotlin/exportedlib.js到 React 应用程序并import exportedlib from './exportedlib'在 App.js 中导入它。

编译时,npm start我会收到以下错误消息:Module not found: Can't resolve 'kotlin'

  1. 然后,我还将 kotlin.js 从build/js/packages_imported/kotlin/1.3.72/kotlin.js导入到 React 应用程序中。

然后我收到错误消息:

./src/kotlin.js
  Line 2:39:      'define' is not defined                                                no-undef
  1. 如上所述没有用,我还在 build.gradle 中添加了浏览器目标并将其导出为gradlew browserDistribution.

然后我从 npm 收到这些错误消息:

./src/exportedlib.js
  Line 1:1:      Expected an assignment or function call and instead saw an expression  no-unused-expressions
  Line 1:112:    'define' is not defined                                                no-undef
  Line 1:123:    'define' is not defined                                                no-undef
  Line 1:500:    Expected an assignment or function call and instead saw an expression  no-unused-expressions
// ... a lot of other "Expected an assignment or function call and instead saw an expression" error messages

谁能帮我导出一个 Kotlin JS 库,以便它可以在 React 应用程序中使用?

这是我的 build.gradle:

plugins {
    id 'org.jetbrains.kotlin.js' version '1.3.72'
}

repositories {
    mavenCentral()
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-js"
    testImplementation "org.jetbrains.kotlin:kotlin-test-js"
}

kotlin.target.nodejs { }

// added as above didn't work
kotlin.target.browser { }

compileKotlinJs.kotlinOptions.moduleKind = "commonjs"

更新

vanyochek的答案在使用 导出时对我有用./gradlew compileProductionExecutableKotlinJs,但仅适用于具有实验性 IR 后端的 Kotlin 1.4 M2。

Kotlin 1.3 的任何解决方案将不胜感激。

4

1 回答 1

2

您可以尝试使用1.4-M2Kotlin 版本和 IR 后端。您需要更改build.gradle文件:

plugins {
    id 'org.jetbrains.kotlin.js' version '1.4-M2'
}

repositories {
    mavenCentral()
    maven { url 'https://dl.bintray.com/kotlin/kotlin-eap' }
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-js"
    testImplementation "org.jetbrains.kotlin:kotlin-test-js"
}

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

        compilations.all {
            kotlinOptions.moduleKind = "commonjs"
        }
    }
}

和 settings.gradle:

pluginManagement {
    repositories {
        maven { url 'https://dl.bintray.com/kotlin/kotlin-eap' }

        mavenCentral()

        maven { url 'https://plugins.gradle.org/m2/' }
    }
}
rootProject.name = 'exportedlib'

JS 编译后,只需添加exportedlib.js到您的 React 项目中。

注意:Kotlin1.4-M2和 IR 后端不稳定。

于 2020-06-22T11:47:44.900 回答