ScalaJS is a library developed using scala can be used to write client side application which run in the browser. It is simply a compiler which converts scala code into java script. So, we write strong typing and fail safe code to generate JavaScript, also scala has some optimization in JavaScript to robust performance. There are other advantages like finding errors in scala code is easier, also makes the refactoring easier, with excellent editor support. The key feature of Scala.js is its interoperability with JavaScript code.
In this article, I am going to give some ideas on how we can start using scala.js and what kind of dependencies we need to write a sample application. I am using scala-cli which actually boosts the process of writing demo application.
- Install scala-cli
- Installation is simple. I have used sdkmann to install it.
- Create a folder called “sacla-js-example”
- Create a file Main.scala
- Create a file Main.scala where we write our frontend scala code.
- Compile it to generate Main.js
- scala-cli package -f . –js-module-kind commonjs –watch
- Include compiled javascript in html (index.html)
- Test (python3 -m http.server)
The running application can be checked using http://localhost:8000/
I prefer using vscode with metals plugin. The basically I have created 2 files: Main.scala, index.html.
Main.scala
//> using scala "3.3.0"
//> using platform "scala-js"
//> using dep org.scala-js:scalajs-dom_sjs1_3:2.8.0
import org.scalajs.dom
import dom.document
object Main {
def main(args: Array[String]): Unit = {
// Ensure the DOM is fully loaded before running the code
dom.document.addEventListener("DOMContentLoaded", { (e: dom.Event) =>
appendPar(document.body, "Hello, Scala.js!")
})
}
def appendPar(targetNode: dom.Node, text: String): Unit = {
val parNode = document.createElement("p")
val textNode = document.createTextNode(text)
parNode.appendChild(textNode)
targetNode.appendChild(parNode)
}
}
The compiling the above code generates Main.js file which need to be included in the html file to see the effects of javascript file.
scala-cli config power true
scala-cli package . --js-module-kind commonjs
So, lets create index.html file and include the Javascript file we just generated.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Scala.js Example</title>
<script src="./Main.js"></script>
</head>
<body>
<h1>Scala.js Example</h1>
</body>
</html>
You can open this file in any browser or you can use the option “Open with live Server option” in vscode.
Or you can simply use the following python command in the project directory to run http server
python3 -m http.server
Now you can test the changes by opening this link in any browser.
http://localhost:8000
