简体   繁体   English

如何在 Scalajs 项目中使用 Javascript 库

[英]How to Use a Javascript Library in a Scalajs Project

I am following the tutorial here:我正在关注这里的教程:

https://www.scala-js.org/doc/project/dependencies.html https://www.scala-js.org/doc/project/dependencies.html

  1. First things first, I have my project set up like this:首先,我的项目设置如下:

https://github.com/scala-js/scalajs-cross-compile-example https://github.com/scala-js/scalajs-cross-compile-example

Without making any changes, this runs as expected when I pass in the following commands:在不进行任何更改的情况下,当我传入以下命令时,它会按预期运行:

sbt> fooJS/run
sbt> fooJVM/run
  1. Now I want to import this library:现在我想导入这个库:

  2. I want to run the following function:我想运行以下 function:

    Plotly.newPlot('myDiv', data); Plotly.newPlot('myDiv', data);

How can I do this?我怎样才能做到这一点?

My Main.scala file inside the js folder looks like this:我的 js 文件夹内的 Main.scala 文件如下所示:

package example

object Main extends App {
  println(s"Using Scala.js version ${System.getProperty("java.vm.version")}")
}

I know a facade for this library already exists, but I would like to be able to create my own facades for future projects, and am using this as an example.我知道这个库的外观已经存在,但我希望能够为未来的项目创建自己的外观,并以此为例。 I read the tutorial here:我在这里阅读了教程:

https://www.scala-js.org/doc/interoperability/facade-types.html https://www.scala-js.org/doc/interoperability/facade-types.html

But in all honesty I do not follow those steps coming from a different language ecosystem.但老实说,我不遵循来自不同语言生态系统的那些步骤。

“I do not follow those steps” is not a useful way to describe the problems you're having. “我不遵循这些步骤”不是描述您遇到的问题的有用方式。

It looks fairly obvious what you need to do.你需要做什么看起来很明显。 There's a global Object called Plotly , which has a method called newPlot , which takes a String and an array of objects containing the data.有一个名为Plotly的全局 Object ,它有一个名为newPlot的方法,它接受一个String和一个包含数据的对象数组。 So you need something like this:所以你需要这样的东西:

@js.native
@JSGlobal
object Plotly extends js.Object {
  def newPlot(id: String, data: js.Array[PlotData]) = js.native
}

Now that we have that, we also need to specify what PlotData is supposed to look like.现在我们有了它,我们还需要指定PlotData应该是什么样子。 Unlike the type of the Plotly object, where we merely specify the interface and the actual object is implemented in JS, this type is going to be implemented in Scala, so you need to follow this guide . Unlike the type of the Plotly object, where we merely specify the interface and the actual object is implemented in JS, this type is going to be implemented in Scala, so you need to follow this guide .

For a scatter type plot, it could look like so:对于scatter类型 plot,它可能如下所示:

case class PlotData(
  x: js.Array[Double],
  y: js.Array[Double]
) extends js.Object {
  def type: String = "scatter"
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM