我正在为 jvm 和 js 创建一个 kotlin mutliplatform 项目。我的 build.gradle.kts 看起来像这样:
plugins {
id ("org.jetbrains.kotlin.multiplatform")
}
repositories {
mavenCentral()
}
kotlin {
jvm() {
compilations["main"].kotlinOptions{
jvmTarget = "1.8"
}
}
js() {
compilations["main"].kotlinOptions{
outputFile = "${buildDir}/nodejs/common.js"
moduleKind = "commonjs"
sourceMap = true
verbose = true
}
}
sourceSets {
val commonMain by getting {
dependencies {
implementation (kotlin("stdlib"))
implementation (kotlin("stdlib-common"))
}
}
val commonTest by getting {
dependencies {
implementation (kotlin("test-common"))
implementation (kotlin("test-annotations-common"))
}
}
jvm().compilations["main"].defaultSourceSet {
dependencies {
implementation (kotlin("stdlib-jdk8"))
}
}
jvm().compilations["test"].defaultSourceSet {
dependencies {
implementation (kotlin("test"))
implementation (kotlin("test-junit"))
}
}
js().compilations["main"].defaultSourceSet {
dependencies {
implementation (kotlin("stdlib-js"))
}
}
js().compilations["test"].defaultSourceSet {
dependencies {
implementation (kotlin("test-js"))
}
}
}
}
当我构建项目时,会创建一个 common.js,其内容如下所示:
(function (_, Kotlin) {
'use strict';
var Kind_CLASS = Kotlin.Kind.CLASS;
var ArrayList_init = Kotlin.kotlin.collections.ArrayList_init_287e2$;
var emptyList = Kotlin.kotlin.collections.emptyList_287e2$;
var NotImplementedError_init = Kotlin.kotlin.NotImplementedError;
function commonSharedCode(platform) {
return 'Common: Hi! ' + platform.greetingMethod + '(' + platform.name + ') AND NOW IN BEAUTIFUL ' + platform.beautifulPlatform();
}
function Platform(greetingMethod, name) {
this.greetingMethod = greetingMethod;
this.name = name;
}
Platform.prototype.beautifulPlatform = function () {
return '***' + this.name + '***';
};
// ... //
return _;
}(module.exports, require('kotlin')));
现在我在项目外创建了一个简单的 javascript 文件并尝试使用创建的代码(就像你在教程中看到的 - 他们创建了一个使用 mutliplatform 项目作为依赖项的应用程序)。这似乎是不可能的,因为创建的代码没有导出函数等。我希望能够做这样的事情
const common = require('common');
function myTest () {
console.log(common.Platform('Hello', 'World'));
}
您对如何构建项目以能够完成这些事情有想法吗?
最佳答案
您是否尝试过实际运行上述代码?如果是,会发生什么?这个问题有些含糊不清,因此很难确定实际问题是什么。
无论如何,让我分享我以一种快速而肮脏的方式设法做的事情。也许这个概念证明会解开你的障碍。
class TestLibraryClass {
@JsName("appendNumberToString")
fun appendNumberToString(string: String, number: Int) =
"Appending: $string - $number"
fun functionWithoutJsNameAnnotation(someStr: String)
= someStr
}
build/distributions/project-name.js
. project-name.js
的代码。像这样的文件 - 这相当于您尝试使用 require
:importedKotlinLib = ...pasted the code here...
[hit enter]
TestLibraryClass
的实例:testLibraryClassInstance = new importedKotlinLib.TestLibraryClass()
我了解了名称修改(以及如何解决它)here .请注意类名
TestLibraryClass
没有被破坏。我测试了顶级函数的名称是否被破坏。关于大局 - 如果官方支持准备用 Kotlin 编写的 JS 库 - 我在这里没有完全清楚。一旦我发现,我很乐意更新这个答案。我也在考虑在我公司的项目中加入 Kotlin/JS。
关于gradle - 如何使用由 kotlin 多平台创建的 Javascript 工件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60187271/