首页 > 解决方案 > 设置一个 scala.js 交叉编译库

问题描述

我有一个小型 Scala 库,我想在 Scala.js 应用程序中使用它:https ://github.com/fbaierl/scala-tarjan

出于这个原因,我决定创建一个可以编译为 Scala.js 和 Scala JVM 的交叉编译库:https ://github.com/fbaierl/scalajs-cross-compile-tarjan 。但我有点坚持如何从这里继续。

到目前为止,我在共享目录中有所有相关代码:

以及这里的 JVM 和 JS 部分的两个Tarjan.scala类:

这些应该是 JVM 和 JS 的公共“接口类”,它们只是从共享库中调用方法。

js/src/main/scala/Tarjan.scala:

import com.github.fbaierl.tarjan.{TarjanRecursive => lib}
import scala.scalajs.js.annotation.{JSExport, JSExportTopLevel}

@JSExportTopLevel("Tarjan")
object Tarjan {
   @JSExport
   def tarjan[T](g: Map[T, List[T]]): Unit = lib.tarjan(g)
}

jvm/src/main/scala/Tarjan.scala:

import com.github.fbaierl.tarjan.{TarjanRecursive => lib}

object Tarjan {
  def tarjan[T](g: Map[T, List[T]]): Unit = lib.tarjan(g)
}

Is this generally the correct approach? Can I compile the project like that and publish to e.g. Sonatype?

标签: scalacross-platformpublishscala.js

解决方案


Instead of duplicating the "interface classes" for JS and JVM, you might want to use the scalajs-stubs library to be able to use @JSExportTopLevel and @JSExport in the shared code.

shared/src/main/scala/Tarjan.scala:

import com.github.fbaierl.tarjan.{TarjanRecursive => lib}
import scala.scalajs.js.annotation.{JSExport, JSExportTopLevel}

@JSExportTopLevel("Tarjan")
object Tarjan {
  @JSExport
  def tarjan[T](g: Map[T, List[T]]): Unit = lib.tarjan(g)
}

build.sbt:

… .jvmSettings(
  libraryDependencies += "org.scala-js" %% "scalajs-stubs" % scalaJSVersion % "provided"
)

See "Exporting shared classes to JavaScript" at the bottom of https://www.scala-js.org/doc/project/cross-build.html.


推荐阅读