![](/img/trans.png)
[英]Scala Scala.js importing JavaScript module gives error 'method value is not a member of'
[英]Scala Scala.js importing JavaScript module gives 'There were linking errors, module support is disabled'
我正在尝试将 JavaScript class 模块script.js
导入 scala 程序main.scala
并使用其方法add
和divide
。
我正在使用 scala.js 导入 JS 脚本,使用 SBT 进行构建。
但是,当我尝试运行该程序时,出现如下错误:
[info] Fast optimizing D:\Studio\...\target\scala-2.13\add-fastopt
[error] example.MyType needs to be imported from module 'script.js' but module support is disabled
[error] called from example.Hello$.work()void
[error] called from example.Hello$.$js$exported$meth$work()java.lang.Object
[error] exported to JavaScript with @JSExport
[error] involving instantiated classes:
[error] example.Hello$
[error] There were linking errors
[error] (Compile / fastLinkJS) There were linking errors
[error] Total time: 82 s (01:22),
你能帮我找出问题所在吗?
提前致谢!
代码看起来像这样!
主要.scala
package example
import scala.scalajs.js
import scala.scalajs.js.annotation._
@js.native
@JSImport("script.js","MyType")
class MyType(var x:Double, var y:Double) extends js.Object {
def add(z: Int): Double = js.native
def divide(z: Int): Double = js.native
}
object Hello extends App {
work()
@JSExport
def work(): Unit = {
val added = new MyType(1,2).add(3)
val divided = new MyType(4,3).divide(2)
println(s"Answers: $added, $divided")
}
}
脚本.js:
class MyType {
constructor(x, y) {
...
}
add(z){
...
}
divide(z){
...
}
};
module.exports = {MyType};
插件.sbt:
addSbtPlugin("org.scala-js" % "sbt-scalajs" % "1.10.0")
addSbtPlugin("org.portable-scala" % "sbt-scalajs-crossproject" % "1.0.0")
build.sbt:
import Dependencies._
ThisBuild / scalaVersion := "2.13.8"
ThisBuild / version := "0.1.0-SNAPSHOT"
ThisBuild / organization := "com.example"
ThisBuild / organizationName := "example"
lazy val root = (project in file("."))
.settings(
name := "add",
libraryDependencies += scalaTest % Test
)
enablePlugins(ScalaJSPlugin)
scalaJSUseMainModuleInitializer := true
// See https://www.scala-sbt.org/1.x/docs/Using-Sonatype.html for instructions on how to publish to Sonatype.
我将linker.interface
模块导入到 build.sbt:
然后在sbt设置中启用了CommonJSModule
和ESModule
。
这对我有用!
build.sbt:
import Dependencies._
import org.scalajs.linker.interface.ModuleInitializer
ThisBuild / scalaVersion := "2.13.8"
ThisBuild / version := "0.1.0-SNAPSHOT"
ThisBuild / organization := "com.example"
ThisBuild / organizationName := "example"
lazy val root = (project in file("."))
.settings(
name := "add",
libraryDependencies += scalaTest % Test
)
enablePlugins(ScalaJSPlugin)
scalaJSUseMainModuleInitializer := true
// ECMAScript
scalaJSLinkerConfig ~= { _.withModuleKind(ModuleKind.ESModule) }
// CommonJS
scalaJSLinkerConfig ~= { _.withModuleKind(ModuleKind.CommonJSModule) }
// See https://www.scala-sbt.org/1.x/docs/Using-Sonatype.html for instructions on how to publish to Sonatype.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.