【问题标题】:What is the right way to call Scala.js from Node.js?从 Node.js 调用 Scala.js 的正确方法是什么?
【发布时间】:2023-03-10 17:44:01
【问题描述】:

从 Node.js 调用 Scala.js 的正确方法是什么?下面的代码确实有效,但我不喜欢 run.js 中 require 行中的 .__ScalaJSExportsNamespace。获取文本“someTest() called!”对我来说也很重要!实际打印在我的终端上。

run.js

var fastopt = require('./scalajs-hello-world-fastopt').__ScalaJSExportsNamespace;
var run = fastopt.RunMe();

run.main();
console.log(run.helloWorld());
console.log(run.someTest());

RunMe.scala

import scala.scalajs.js.annotation._
import scala.scalajs.js.JSApp

@JSExportAll
object RunMe extends JSApp {

  def main(): Unit = {
    println("Hello from main()!")
  }

  def helloWorld() = "Hello from helloWorld()!"

  def someTest() = {
    println("someTest() called!")
    s"In Scala.js, (1.0).toString is ${(1.0).toString}!"
  }

}

输出

$ node run  
Hello from main()!
Hello from helloWorld()!
someTest() called!
In Scala.js, (1.0).toString is 1!

【问题讨论】:

  • 从节点调用 Scala.js 的最佳方法是将 Scala.js 的导出命名空间设置为 exports。这实际上将使它成为一个适当的节点模块。您使用的是哪个 Scala.js 版本? (看起来它比较旧,IIRC __ScalaJSExportsNamespace 在以后的版本中不再存在)。
  • @gzm0:我使用的是 Scala.js 0.6.4 和 Scala 2.11.7。应该是最新版本。我从你那里找到了答案(1)。这仍然是要走的路吗?您是否使用 Grunt 来添加导出命名空间? (1)stackoverflow.com/questions/26637600/…
  • 是的,这仍然是要走的路。您可以使用任何您喜欢的工具来执行此操作。我个人会使用 sbt,只是因为我最熟悉它。
  • @gzm0 你有一个示例 sbt 来为我添加代码 sn-p 吗?
  • @user1091344 gist.github.com/chandu0101/a92a9d7fd60ac741ca41,这有意义吗?

标签: javascript node.js scala scala.js


【解决方案1】:

您可以通过将以下内容添加到构建文件(从 Scala.js 0.6.5 开始)来配置 Scala.js 以创建 CommonJS 样式模块:

scalaJSOutputWrapper := ("var __ScalaJSEnv = { exportsNamespace: exports };", "")

更多详情请关注this SO post

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-19
    相关资源
    最近更新 更多