Integrating Scala-JS into an existing project, part 2

After integrating basic scalajs support into the project (part 1), we now want to include the following libraries (described here):

  • dom for manipulating the DOM structure of the HTML page
  • jquery to have an easier access to the DOM. And of course, we want to use the shortcut "$" instead of the verbose jQuery

To do so, add the following settings to your mainprojectfolder/build.sbt file describing the js project defined in the last article.

lazy val js = (project in file("js")).enablePlugins(ScalaJSPlugin).settings(
  libraryDependencies += "org.scala-js" %%% "scalajs-dom" % "0.8.0",
  libraryDependencies += "be.doeraene" %%% "scalajs-jquery" % "0.8.0"

This is the safest way to ensure that the libraries are imported.
Now in your scala file compiling to javascript (myscript.scala), you can include these import statements:

package your.package
import org.scalajs.dom
import dom.document
import org.scalajs.jquery.{ jQuery => $ }
import scala.scalajs.js.annotation.JSExport

object YourApp extends JSApp {
  @JSExport def addClickedMessage(): Unit = {
    val message = "You clicked the button!"
    //appendPar(document.body, message) (DOM version)
  def main(): Unit = {
    println("Hello world!")

Now in your html you can include something like this, and this will work:

<button id="click-me-button" type="button" onclick="your.package.YourApp().addClickedMessage()">Click me!</button>

I hope that you will enjoy Scala-js as much as I do !