Kotlin编译成不可命名的javascript

Kotlin编译成不可命名的javascript,javascript,kotlin,Javascript,Kotlin,我在kotlin中有一个项目(即,示例kotlin项目),该项目正在使用gradle和以下gradle脚本编译为javascript: buildscript { ext.kotlin_version = '1.1.4-3' repositories { mavenCentral() maven { url "https://plugins.gradle.org/m2/" } } dependencies { cl

我在kotlin中有一个项目(即,
示例kotlin项目
),该项目正在使用gradle和以下gradle脚本编译为javascript:

buildscript {
    ext.kotlin_version = '1.1.4-3'

    repositories {
        mavenCentral()
        maven { url "https://plugins.gradle.org/m2/" }
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath 'com.moowork.gradle:gradle-node-plugin:1.2.0'
    }
}

apply plugin: 'kotlin2js'
apply plugin: 'com.moowork.node'

repositories {
    mavenCentral()
}

dependencies {
    compile "org.jetbrains.kotlin:kotlin-stdlib-js:$kotlin_version"
    testCompile "org.jetbrains.kotlin:kotlin-test-js:$kotlin_version"
}

task wrapper(type: Wrapper) {
    gradleVersion = "4.1"
}

[compileKotlin2Js, compileTestKotlin2Js]*.configure {
    kotlinOptions.moduleKind = "commonjs"
}
执行
gradle clean build
后,我得到以下工件:

  • kotlin.js
  • sample-kotlin-project_main.js
  • 并将它们导入html文件
    index.html

    <html>
    
    <head>
        <script src="<path-to-target>/kotlin.js"></script>
    </head>
    
    <body>
        <script src="<path-to-target>/sample-kotlin-project_main.js"></script>
    </body>
    </html>
    
    这似乎是浏览器的一个问题。
    sample-kotlin-project_main.js中的以下行出错:

    Uncaught ReferenceError: module is not defined
    
      Kotlin.defineModule('sample-kotlin-project_main', _);
      return _;
    }(module.exports, require('kotlin')));
    
    我的问题是:为什么会发生这种情况以及应该做些什么来解决这个问题


    事先非常感谢。

    您需要模块加载器以及kotlin JS文件。您可以选择AMD(RequireJS等)、UMD或CommonJS。请参阅以获得澄清。您能详细说明gradle集成以实现这一点吗?更新:在编译到commonjs时,似乎不需要使用导入。相反,您必须在其他js文件中使用require('your_kt_file')