This page applies only to Scala.js 0.6.x. Go the newer tutorial for Scala.js 1.x.

This is a step-by-step tutorial where we start with the setup of a Scala.js sbt project and end up having some user interaction and unit testing. The code created in this tutorial is available with one commit per step in the scalajs-tutorial repository on GitHub.

Step 0: Prerequisites

To go through this tutorial, you will need to download & install sbt. Note that no prior sbt knowledge (only a working installation) is required to follow the tutorial.

You will also need to download & install Node.js.

Step 1: Setup

First create a new folder where your sbt project will go.

sbt Setup

To setup Scala.js in a new sbt project, we need to do two things:

  • Add the Scala.js sbt plugin to the build
  • Enable the plugin in the projectAdding the Scala.js sbt plugin is a one-liner in project/plugins.sbt (all file names we write in this tutorial are relative to the project root):
  1. addSbtPlugin("org.scala-js" % "sbt-scalajs" % "0.6.32")

We also setup basic project settings and enable this plugin in the sbt build file (build.sbt, in the project root directory):

  1. enablePlugins(ScalaJSPlugin)
  2. name := "Scala.js Tutorial"
  3. scalaVersion := "2.13.1" // or any other Scala version >= 2.10.2
  4. // This is an application with a main method
  5. scalaJSUseMainModuleInitializer := true

Last, we need a project/build.properties to specify the sbt version (you can find the latest version here):

  1. sbt.version=1.3.7

That is all we need to configure the build.

If at this point you prefer to use an IDE, you can import the build into VS Code with Metals (or any other editor supported by Metals) or IntelliJ IDEA (see “Installation” here).Note that for compiling and running your application, you will still need to use sbt from the command line.

HelloWorld application

For starters, we add a very simple TutorialApp in the tutorial.webapp package. Create the file src/main/scala/tutorial/webapp/TutorialApp.scala:

  1. package tutorial.webapp
  2. object TutorialApp {
  3. def main(args: Array[String]): Unit = {
  4. println("Hello world!")
  5. }
  6. }

As you expect, this will simply print “HelloWorld” when run. To run this, simply launch sbt and invoke the run task:

  1. $ sbt
  2. sbt:Scala.js Tutorial> run
  3. [info] Compiling 1 Scala source to (...)/scalajs-tutorial/target/scala-2.13/classes ...
  4. [info] Fast optimizing (...)/scalajs-tutorial/target/scala-2.13/scala-js-tutorial-fastopt.js
  5. [info] Running tutorial.webapp.TutorialApp
  6. Hello world!
  7. [success] (...)

Congratulations! You have successfully compiled and run your first Scala.js application.The code is actually run by a JavaScript interpreter, namely Node.

Source maps in Node.js: To get your stack traces resolved on Node.js, you will have to install the source-map-support package.

  1. $ npm install source-map-support

Step 2: Integrating with HTML

Now that we have a simple JavaScript application, we would like to use it in an HTML page. To do this, we need two steps:

  • Generate a single JavaScript file out of our compiled code
  • Create an HTML page which includes that file

Generate JavaScript

To generate a single JavaScript file using sbt, just use the fastOptJS task:

  1. > fastOptJS
  2. [info] Fast optimizing (...)/scalajs-tutorial/target/scala-2.13/scala-js-tutorial-fastopt.js
  3. [success] (...)

This will perform some fast optimizations and generate the target/scala-2.13/scala-js-tutorial-fastopt.js file containing the JavaScript code.

(It is possible that the [info] does not appear, if you have just run the program and not made any change to it.)

Create the HTML Page

To load and launch the created JavaScript, you will need an HTML file. Create the file scalajs-tutorial-fastopt.html (or whatever name you prefer, for example index-dev.html) in the project root with the following content. We will go in the details right after.

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>The Scala.js Tutorial</title>
  6. </head>
  7. <body>
  8. <!-- Include Scala.js compiled code -->
  9. <script type="text/javascript" src="./target/scala-2.13/scala-js-tutorial-fastopt.js"></script>
  10. </body>
  11. </html>

The script tag simply includes the generated code (attention, you might need to adapt the Scala version from 2.13 to 2.12 (or even 2.10 or 2.11) here if you are using an older version of Scala).

Since we have set scalaJSUseMainModuleInitializer := true in the build, the TutorialApp.main(args: Array[String]) method is automatically called at the end of the -fastopt.js file (with an empty array as argument).

If you now open the newly created HTML page in your favorite browser, you will see … nothing. The println in the main method goes right to the JavaScript console, which is not shown by default in a browser. However, if you open the JavaScript console (e.g. in Chrome: right click -> Inspect Element -> Console) you can see the HelloWorld message.

Step 3: Using the DOM

As the last step has shown, running JavaScript inside an HTML page is not particularly useful if you cannot interact with the page.That’s what the DOM API is for.

Adding the DOM Library

To use the DOM, it is best to use the statically typed Scala.js DOM library. To add it to your sbt project, add the following line to your build.sbt:

  1. libraryDependencies += "org.scala-js" %%% "scalajs-dom" % "1.0.0"

sbt-savvy folks will notice the %%% instead of the usual %%. It means we are using a Scala.js library and not anormal Scala library. Have a look at the Dependencies guide for details. Don’t forgetto reload the build file if sbt is still running:

  1. sbt:Scala.js Tutorial> reload
  2. [info] Loading settings for project global-plugins from plugins.sbt ...
  3. [info] Loading global plugins from (...)/.sbt/1.0/plugins
  4. [info] Loading settings for project scalajs-tutorial-build from plugins.sbt ...
  5. [info] Loading project definition from (...)/scalajs-tutorial/project
  6. [info] Loading settings for project scala-js-tutorial from build.sbt ...
  7. [info] Set current project to Scala.js Tutorial (in build file:(...)/scalajs-tutorial/)

If you are using an IDE plugin, you will also have to reimport the build for autocompletion to work.

Using the DOM Library

Now that we added the DOM library, let’s adapt our HelloWorld example to add a <p> tag to the body of the page, rather than printing to the console.

First of all, we import a couple of things:

  1. import org.scalajs.dom
  2. import org.scalajs.dom.document

dom is the root of the JavaScript DOM and corresponds to the global scope of JavaScript (aka the window object).We additionally import document (which corresponds to document in JavaScript) for convenience.

We now create a method that allows us to append a <p> tag with a given text to a given node:

  1. def appendPar(targetNode: dom.Node, text: String): Unit = {
  2. val parNode = document.createElement("p")
  3. val textNode = document.createTextNode(text)
  4. parNode.appendChild(textNode)
  5. targetNode.appendChild(parNode)
  6. }

Replace the call to println with a call to appendPar in the main method:

  1. def main(args: Array[String]): Unit = {
  2. appendPar(document.body, "Hello World")
  3. }

Rebuild the JavaScript

To rebuild the JavaScript, simply invoke fastOptJS again:

  1. sbt:Scala.js Tutorial> fastOptJS
  2. [info] Compiling 1 Scala source to (...)/scalajs-tutorial/target/scala-2.13/classes ...
  3. [info] Fast optimizing (...)/scalajs-tutorial/target/scala-2.13/scala-js-tutorial-fastopt.js
  4. [success] (...)

As you can see from the log, sbt automatically detects that the sources must be recompiled before fast optimizing.

You can now reload the HTML in your browser and you should see a nice “Hello World” message.

Re-typing fastOptJS each time you change your source file is cumbersome. Luckily sbt is able to watch your files and recompile as needed:

  1. sbt:Scala.js Tutorial> ~fastOptJS
  2. [success] (...)
  3. [info] 1. Monitoring source files for scalajs-tutorial/fastOptJS...
  4. [info] Press <enter> to interrupt or '?' for more options.

From this point in the tutorial we assume you have an sbt with this command running, so we don’t need to bother with rebuilding each time.

Step 4: Reacting on User Input

This step shows how you can add a button and react to events on it by still just using the DOM (we will use jQuery in the next step). We want to add a button that adds another <p> tag to the body when it is clicked.

We start by adding a method to TutorialApp which will be called when the button is clicked:

  1. @JSExportTopLevel("addClickedMessage")
  2. def addClickedMessage(): Unit = {
  3. appendPar(document.body, "You clicked the button!")
  4. }

You will notice the @JSExportTopLevel annotation.It tells the Scala.js compiler to make that method callable as top-level function from JavaScript. We must also import this annotation:

  1. import scala.scalajs.js.annotation.JSExportTopLevel

To find out more about how to call Scala.js methods from JavaScript, have a look at the Export Scala.js API toJavaScript guide.

Since we now have a method that is callable from JavaScript, all we have to do is add a button to our HTML and set itsonclick attribute (make sure to add the button before the <script> tags):

  1. <button id="click-me-button" type="button" onclick="addClickedMessage()">
  2. Click me!
  3. </button>

Reload your HTML page (remember, sbt compiles your code automatically) and try to click the button. It should add a newparagraph saying “You clicked the button!” each time you click it.

Step 5: Using jQuery

Larger web applications have a tendency to set up reactions to events in JavaScript rather than specifying attributes.We will transform our current mini-application to use this paradigm with the help of jQuery. Also we will replace allusages of the DOM API with jQuery.

Depending on jQuery

Just like for the DOM, there is a typed library for jQuery available in Scala.js: scalajs-jquery (there is a livelier fork which you may prefer if it already supports the version of Scala you are using).Add the following line in your build.sbt by:

  1. libraryDependencies += "be.doeraene" %%% "scalajs-jquery" % "1.0.0"

Don’t forget to reload the sbt configuration now:

  • Hit enter to abort the ~fastOptJS command
  • Type reload
  • Start ~fastOptJS againAgain, make sure to update your IDE project files if you are using a plugin.

Using jQuery

In TutorialApp.scala, remove the imports for the DOM, and add the import for jQuery:

  1. import org.scalajs.jquery._

This allows you to easily access the jQuery main object of jQuery in your code (also known as $).

We can now remove appendPar and replace all calls to it by the simple:

  1. jQuery("body").append("<p>[message]</p>")

Where [message] is the string originally passed to appendPar, for example:

  1. jQuery("body").append("<p>Hello World</p>")

If you try to reload your webpage now, it will not work (typically a TypeError would be reported in the console). Theproblem is that we haven’t included the jQuery library itself, which is a plain JavaScript library.

Adding JavaScript libraries

An option is to include jquery.js from an external source, such as jsDelivr.

  1. <script type="text/javascript" src="http://cdn.jsdelivr.net/jquery/2.2.1/jquery.js"></script>

This can easily become very cumbersome, if you depend on multiple libraries. The Scala.js sbt plugin provides amechanism for libraries to declare the plain JavaScript libraries they depend on and bundle them in a single file. Allyou have to do is activate this and then include the file.

In your build.sbt, set:

  1. skip in packageJSDependencies := false
  2. jsDependencies +=
  3. "org.webjars" % "jquery" % "2.2.1" / "jquery.js" minified "jquery.min.js"

After reloading and rerunning fastOptJS, this will create scala-js-tutorial-jsdeps.js containing all JavaScriptlibraries next to the main JavaScript file. We can then simply include this file and don’t need to worry aboutJavaScript libraries anymore:

  1. <!-- Include JavaScript dependencies -->
  2. <script type="text/javascript" src="./target/scala-2.13/scala-js-tutorial-jsdeps.js"></script>

Setup UI in Scala.js

We still want to get rid of the onclick attribute of our <button>. After removing the attribute, we add thesetupUI method, in which we use jQuery to add an event handler to the button. We also move the “Hello World” messageinto this function.

  1. def setupUI(): Unit = {
  2. jQuery("body").append("<p>Hello World</p>")
  3. jQuery("#click-me-button").click(() => addClickedMessage())
  4. }

Since we do not call addClickedMessage from plain JavaScript anymore, we can remove the @JSExportTopLevel annotation (and the corresponding import).

Finally, we add a last call to jQuery in the main method, in order to execute setupUI, once the DOM is loaded:

  1. def main(args: Array[String]): Unit = {
  2. jQuery(() => setupUI())
  3. }

Again, since we are not calling setupUI directly from plain JavaScript, we do not need to export it (even thoughjQuery will call it through that callback).

We now have an application whose UI is completely setup from within Scala.js. The next step will show how we can testthis application.

Step 6: Testing

In this section we will show how such an application can be tested using uTest, atiny testing framework which compiles to both Scala.js and Scala JVM. As a note aside, this framework is also a goodchoice to test libraries that cross compile. See our cross compilation guide fordetails.

Supporting the DOM

Before we start writing tests which we will be able to run through the sbt console, we first have to solve anotherissue. Remember the task run? If you try to invoke it now, you will see something like this:

  1. > run
  2. [info] Running tutorial.webapp.TutorialApp
  3. [error] TypeError: (0 , $m_Lorg_scalajs_jquery_package$(...).jQuery$1) is not a function
  4. [error] at $c_Ltutorial_webapp_TutorialApp$.main__AT__V (.../TutorialApp.scala:9:11)
  5. [error] ...
  6. [trace] Stack trace suppressed: run last compile:run for the full output.
  7. [error] (compile:run) org.scalajs.jsenv.ExternalJSEnv$NonZeroExitException: Node.js exited with code 1
  8. [error] Total time: 1 s, completed Oct 13, 2016 3:06:00 PM

What basically happens here is that jQuery (which is automatically included because of jsDependencies) cannot properly load, because there is no DOM available in Node.js.To make the DOM available, add the following to your build.sbt:

  1. jsEnv := new org.scalajs.jsenv.jsdomnodejs.JSDOMNodeJSEnv()

This will use the jsdom library to simulate a DOM in Node.js.Note that you need to install it separately using

  1. $ npm install jsdom

After reloading, you can invoke run successfully:

  1. > run
  2. [info] Running tutorial.webapp.TutorialApp
  3. [success] (...)

Alternatively to Node.js with jsdom, you can use PhantomJS or even Selenium.You can find more information about this in the documentation about JavaScript environments.

Adding uTest

Using a testing framework in Scala.js is not much different than on the JVM.It typically boils down to two sbt settings in the build.sbt file.For uTest, these are:

  1. libraryDependencies += "com.lihaoyi" %%% "utest" % "0.7.4" % "test"
  2. testFrameworks += new TestFramework("utest.runner.Framework")

We are now ready to add a first simple test suite (src/test/scala/tutorial/webapp/TutorialTest.scala):

  1. package tutorial.webapp
  2. import utest._
  3. import org.scalajs.jquery._
  4. object TutorialTest extends TestSuite {
  5. // Initialize App
  6. TutorialApp.setupUI()
  7. def tests = Tests {
  8. test("HelloWorld") {
  9. assert(jQuery("p:contains('Hello World')").length == 1)
  10. }
  11. }
  12. }

This test uses jQuery to verify that our page contains exactly one <p> element which contains the text “Hello World”after the UI has been set up.

To run this test, simply invoke the test task:

  1. > test
  2. [info] Compiling 1 Scala source to (...)/scalajs-tutorial/target/scala-2.13/test-classes...
  3. [info] Fast optimizing (...)/scalajs-tutorial/target/scala-2.13/scala-js-tutorial-test-fastopt.js
  4. -------------------------------- Running Tests --------------------------------
  5. + tutorial.webapp.TutorialTest.HelloWorld 2ms
  6. Tests: 1, Passed: 1, Failed: 0
  7. [success] Total time: 14 s, completed 16-mars-2018 20:04:28

We have successfully created a simple test.Just like run, the test task uses Node.js to execute your tests.

A more complex test

We also would like to test the functionality of our button. For this we face another small issue: the button doesn’texist when testing, since the tests start with an empty DOM tree. To solve this, we create the button in the setupUImethod and remove it from the HTML:

  1. jQuery("""<button type="button">Click me!</button>""")
  2. .click(() => addClickedMessage())
  3. .appendTo(jQuery("body"))

This brings another unexpected advantage: We don’t need to give it an ID anymore but can directly use the jQuery objectto install the on-click handler.

We now define the ButtonClick test just below the HelloWorld test:

  1. test("ButtonClick") {
  2. def messageCount =
  3. jQuery("p:contains('You clicked the button!')").length
  4. val button = jQuery("button:contains('Click me!')")
  5. assert(button.length == 1)
  6. assert(messageCount == 0)
  7. for (c <- 1 to 5) {
  8. button.click()
  9. assert(messageCount == c)
  10. }
  11. }

After defining a helper method that counts the number of messages, we retrieve the button from the DOM and verify wehave exactly one button and no messages. In the loop, we simulate a click on the button and then verify that the numberof messages has increased.

You can now call the test task again:

  1. > test
  2. [info] Compiling 1 Scala source to (...)/scalajs-tutorial/target/scala-2.13/test-classes...
  3. [info] Fast optimizing (...)/scalajs-tutorial/target/scala-2.13/scala-js-tutorial-test-fastopt.js
  4. -------------------------------- Running Tests --------------------------------
  5. + tutorial.webapp.TutorialTest.HelloWorld 3ms
  6. + tutorial.webapp.TutorialTest.ButtonClick 6ms
  7. Tests: 2, Passed: 2, Failed: 0
  8. [success] Total time: 15 s, completed 16-mars-2018 20:07:33

This completes the testing part of this tutorial.

Step 7: Optimizing for Production

Here we show a couple of things you might want to do when you promote your application to production.

Full Optimization

Size is critical for JavaScript code on the web. To compress the compiled code even further, the Scala.js sbt pluginuses the advanced optimizations of the Google Closure Compiler. To runfull optimizations, simply use the fullOptJS task:

  1. > fullOptJS
  2. [info] Full optimizing (...)/scalajs-tutorial/target/scala-2.13/scala-js-tutorial-opt.js
  3. [info] Closure: 0 error(s), 0 warning(s)
  4. [success] (...)

Note that this can take a while on a larger project (tens of seconds), which is why we typically don’t use fullOptJSduring development, but fastOptJS instead. If you want to run and test the full-optimized version from sbt,you need to change the stage using the following sbt setting:

  1. > set scalaJSStage in Global := FullOptStage

(by default, the stage is FastOptStage)

We also need to create our final production HTML file scalajs-tutorial.html which includes the fully optimized code:

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>The Scala.js Tutorial</title>
  6. </head>
  7. <body>
  8. <!-- Include JavaScript dependencies -->
  9. <script type="text/javascript" src="./target/scala-2.13/scala-js-tutorial-jsdeps.js"></script>
  10. <!-- Include Scala.js compiled code -->
  11. <script type="text/javascript" src="./target/scala-2.13/scala-js-tutorial-opt.js"></script>
  12. </body>
  13. </html>

Compression

If you serve your Scala.js application from a web server, you should additionallygzip the resulting .js files. This step might reduce the size of your application downto 20% of its original size.

The setup depends on your server stack. A common option is to usesbt-web,sbt-web-scalajs andsbt-gzipif you have a Play or Akka-http server.

This completes the Scala.js tutorial. Refer to our documentation page for deeper insights into variousaspects of Scala.js.