Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you actually run scalajs code in nodejs?

I'm developing a backend chat server. It's currently written in messy callback javascript so I'm considering porting it to scalajs.

I've been looking through the beginner's guides, but I can't find how to actually compile the project to a single javascript file that I can run with node (e.g. node ./target/scala_2.11/my-project.js).

How do you compile a single file that you can run directly as a node program, and not in the browser?

My code couldn't be simpler:

package example

import scala.scalajs.js
import js.Dynamic.{ global => g }

object ScalaJSExample extends js.JSApp {
  def main(): Unit = {
    g.console.log("*** Did something ***")
    println("Trying to print something...")
  }
}

sbt run correctly prints:

*** Did something ***
Trying to print something...

But when I run sbt fullOptJS and then node ./target/scala-2.11/example-opt.js nothing is printed to the console.

like image 951
jbrown Avatar asked Oct 26 '25 16:10

jbrown


1 Answers

The example-opt.js does not contain the one line of JavaScript used to actually launch the code. It only defines example.ScalaJSExample().main() as a function, but it doesn't call it.

An easy way to make it call that function automatically is to instruct sbt to add the call at the end of the .js file with this sbt setting:

scalaJSOutputWrapper := ("", "example.ScalaJSExample().main();")

This will allow you to just invoke

node ./target/scala-2.11/example-opt.js
like image 121
sjrd Avatar answered Oct 29 '25 05:10

sjrd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!