2

What is the right way to call Scala.js from Node.js? The code below does work, but I don't like the .__ScalaJSExportsNamespace in the require line in run.js. Also is it important for me to get the text "someTest() called!" actually printed on my terminal.

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}!"
  }

}

Output

$ node run  
Hello from main()!
Hello from helloWorld()!
someTest() called!
In Scala.js, (1.0).toString is 1!
user1091344
  • 612
  • 6
  • 27
  • The best way to call Scala.js from node is to set Scala.js' export namespace to `exports`. This will actually make it a proper node module. Which Scala.js version are you using? (It looks like it is older, IIRC `__ScalaJSExportsNamespace` does not exist in later versions anymore). – gzm0 Aug 12 '15 at 20:44
  • @gzm0: I am using Scala.js 0.6.4 and Scala 2.11.7. Should be the newest versions. I found an answer (1) from you. Is this still the way to go? Do you use Grunt to prepend the export namespace? (1) http://stackoverflow.com/questions/26637600/how-to-convert-scala-js-application-to-commonjs-module – user1091344 Aug 12 '15 at 21:12
  • Yes, this is still the way to go. You can use whatever tool you like to do so. I'd personally use sbt, just because I'm most familiar with it. – gzm0 Aug 12 '15 at 21:46
  • @gzm0 Do you have an example sbt for prepending the code snippet for me? – user1091344 Aug 12 '15 at 21:53
  • @user1091344 https://gist.github.com/chandu0101/a92a9d7fd60ac741ca41 ,does this makes sense ? – invariant Aug 14 '15 at 02:17

1 Answers1

1

You can configure Scala.js to create a CommonJS style module by adding the following to your build file (starting with Scala.js 0.6.5):

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

More details on this SO post.

Community
  • 1
  • 1
gzm0
  • 14,752
  • 1
  • 36
  • 64