javascript – 与KotlinJs集成的Angular 6打字稿

我刚刚设法在一个有角度的6个打字稿文件中导入Kotlin编译的javascript模块.这并不容易,结果让我感到困惑.我想知道是否存在更优雅的方式.

最初我带了一个Kotlin文件:

package com.example.test

data class SomeInterface(
    var id: String? = null,
    var value: String? = null
) {
}

它很好地编译为以下JavaScript

(function (root, factory) {
  if (typeof define === 'function' && define.amd)
    define(['exports', 'kotlin'], factory);
  else if (typeof exports === 'object')
    factory(module.exports, require('kotlin'));
  else {
    if (typeof kotlin === 'undefined') {
      throw new Error("Error loading module 'TestKotlinCompiled'. Its dependency 'kotlin' was not found. Please, check whether 'kotlin' is loaded prior to 'TestKotlinCompiled'.");
    }
    root.TestKotlinCompiled = factory(typeof TestKotlinCompiled === 'undefined' ? {} : TestKotlinCompiled, kotlin);
  }
}(this, function (_, Kotlin) {
  'use strict';
  var Kind_CLASS = Kotlin.Kind.CLASS;
  function SomeInterface(id, value) {
    if (id === void 0)
      id = null;
    if (value === void 0)
      value = null;
    this.id = id;
    this.value = value;
  }
  SomeInterface.$metadata$= {
    kind: Kind_CLASS,
    simpleName: 'SomeInterface',
    interfaces: []
  };
  SomeInterface.prototype.component1 = function () {
    return this.id;
  };
  SomeInterface.prototype.component2 = function () {
    return this.value;
  };
  SomeInterface.prototype.copy_rkkr90$= function (id, value) {
    return new SomeInterface(id === void 0 ? this.id : id, value === void 0 ? this.value : value);
  };
  SomeInterface.prototype.toString = function () {
    return 'SomeInterface(id=' + Kotlin.toString(this.id) + (', value=' + Kotlin.toString(this.value)) + ')';
  };
  SomeInterface.prototype.hashCode = function () {
    var result = 0;
    result = result * 31 + Kotlin.hashCode(this.id) | 0;
    result = result * 31 + Kotlin.hashCode(this.value) | 0;
    return result;
  };
  SomeInterface.prototype.equals = function (other) {
    return this === other || (other !== null && (typeof other === 'object' && (Object.getPrototypeOf(this) === Object.getPrototypeOf(other) && (Kotlin.equals(this.id, other.id) && Kotlin.equals(this.value, other.value)))));
  };
  var package$com = _.com || (_.com = {});
  var package$example = package$com.example || (package$com.example =     {});
  var package$test = package$example.test || (package$example.test = {});
  package$test.SomeInterface = SomeInterface;
  Kotlin.defineModule('TestKotlinCompiled', _);
  return _;
}));

在package.json中,我将“kotlin”:“^ 1.2.70”添加到依赖项部分.
在角度组件中,我必须使用这样的代码进行导入.

import * as TestKotlinCompiled from "../../generated/TestKotlinCompiled";

// @ts-ignore
const SomeInterface = TestKotlinCompiled.com.example.test.SomeInterface;
// @ts-ignore
type SomeInterface = TestKotlinCompiled.com.example.test.SomeInterface;

这是在模块TestKotlinCompiled中生成的包com.example.test中使用类SomeInterfac的最小强制性代码.

这里的问题如下.

// @ ts-ignore是必需的,因为在编译时ts-comiler没有看到正在导入的模块的内容.

const是新的SomeInterface()所必需的

let x:SomeInterface需要type;

所有这些看起来非常黑客.
我喜欢更喜欢的东西
使用没有const和type的命名空间com.example.test从’../../generated/TestKotlinCompiled’导入{SomeInterface}.
那么,有没有办法简化我的上述代码?

解决方法:

我成功地改善了Angular中KotlinJs的一点点可用性.我在https://github.com/svok/kotlin-multiplatform-sample处理了我的实验

首先,我们必须在Gradle中创建一个多平台子模块.在那里我们生成js文件(以及其他可能的平台).

然后我们添加到package.json …

{
  "dependencies": {
    "kotlin": "^1.3.21",
    "proj-common": "file:../build/javascript-compiled"
  }
}

proj-common是我们编译的Kotlin模块.那里的路径是kotlin-js文件的构建目的地.

因此,在打字稿中我们只使用一个npm模块

import {sample} from 'proj-common/proj-common';

// For class Sample
sample = new sample.Sample();

// For object Platform
platform = sample.Platform;

编译顺利,没有必要使用// @ ts-ignore

更新

在上面的解释中存在子依赖性的问题.它们未被导出,但并非所有子依赖项都在npm存储库中具有等价物.以下代码解决了这个问题.

tasks {
    task<Sync>("assembleWeb") {
        val dependencies = configurations.get("jsMainImplementation").map {
            val file = it
            val (tDir, tVer) = "^(.*)-([\\d.]+-\\w+|[\\d.]+)\\.jar$"
                .toRegex()
                .find(file.name)
                ?.groupValues
                ?.drop(1)
                ?: listOf("", "")
            var jsFile: File? = null
            copy {
                from(zipTree(file.absolutePath), {
                    includeEmptyDirs = false
                    include { fileTreeElement ->
                        val path = fileTreeElement.path
                        val res = (path.endsWith(".js") || path.endsWith(".map"))
                                && (path.startsWith("META-INF/resources/") || !path.startsWith("META-INF/"))
                        if (res && path.endsWith(".js") && ! path.endsWith(".meta.js")) jsFile = fileTreeElement.file
                        res
                    }
                })
                into("$npmTarget/$tDir")
            }
            jsFile?.also { packageJson(tDir, it, tVer) }
            tDir to jsFile
        }
            .filter { it.second != null }
            .map { it.first to it.second!! }
            .toMap()

        packageJson(npmDir, File(jsOutputFile), project.version.toString(), dependencies)
        dependsOn("jsMainClasses")
    }

    assemble.get().dependsOn("assembleWeb")
}

fun packageJson(dir: String, jsFile: File, version: String, dependencies: Map<String, File> = emptyMap()) {
    val deps = dependencies.map {
        """"${js2Name(it.value)}": "file:../${it.key}""""
    }.joinToString(",\n            ")
    val text = """
        {
          "name": "${js2Name(jsFile)}",
          "version": "${version}",
          "main": "./${jsFile.name}",
          "dependencies": {
            ${deps}
          }
        }
    """.trimIndent()
    File("$npmTarget/$dir/package.json").apply {
        if (parentFile.exists()) {
            parentFile.delete()
        }
        parentFile.mkdirs()
        writeText(text)
    }
}

fun js2Name(jsFile: File) = jsFile.name.replace("""\.js$""".toRegex(), "")

然后,从前面的子模块导入:

{
  "dependencies": {
    "proj-common": "file:../build/npm"
  }
}

在typescript文件中:

import {sample} from 'proj-common';

// For class Sample
sample = new sample.Sample();

// For object Platform
platform = sample.Platform;

示例项目见https://github.com/svok/kotlin-multiplatform-sample

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐