Scala.js & friendsSCALA
ALL THETHINGSChris Birchall
Content API team
Nightwatch
Nightwatch: a perfectly good app
● Node.js + Server Sent Events● Concise, well written JavaScript● Reliable● Only one problem…
IT’S NOTWRITTEN IN
SCALA
Scala.js to the rescue
● Compile Scala code to JS○ Implemented as a compiler plugin
● Supports almost any Scala code● Interop with 3rd-party JS libs
○ (with a bit of boilerplate)● Generated JS size is not outrageous
○ Hello world is about 100k
Credit: scala-js.org
Hello world in 2 slides
Hello world in 2 slides
3rd-party JS interop
● Use js.Dynamic○ i.e. throw type safety out of the window○ Quick to write, feels like writing normal JS
● Write a Scala facade for your JS lib○ Typesafe, assuming the facade matches the JS
js.Dynamic
Scala facade
Dependency management
● Facades can be published and shared
● Also support for WebJars● The sbt plugin can write all deps to a single
.js file, à la browserify
libraryDependencies +="be.doeraene" %%% "scalajs-jquery" % "0.8.0"
TRIPLE SQUIGGLE!
<script src=”my-scalajs-app-jsdeps.js”></script><script src=”my-scalajs-app.js”></script>
Scala.js-ifying Nightwatch
● Untyped hashes → case classes● Scala facades for moment.js, Rickshaw● JS if/else chains → Scala pattern matching● uPickle for JSON deserialization
Scala.js-ifying NightwatchBefore 106 lines of JS After 216 lines of Scala
Facades
Case classes
Chained if/else -> pattern match
Before After
Problems along the way
● Obscure Scala.js bugs○ e.g. .className doesn’t work sometimes
● Unexpected uPickle behaviour● Trial and error getting facades to work
○ Gave up and settled on facade + Dynamic hybrid● Brainmelt from Scala/JS context switching
○ e.g. trying to write Scala strings with single quotes
(All in all, > 5 hours to port 100 lines of code)
Credit: The Atlantic
Result: Kinda sorta typesafe JavaScript!
Hang on a sec
What’s this?
CSS?
But...
IT’S NOTWRITTEN IN
SCALA
ScalaCSS to the rescue?
Erm, no.
DSL is virtually undocumented
Gave up after a bit of fruitless trial and error.
Not quite ready for primetime.
On to the next victim
IT’S NOTWRITTEN IN
SCALA
There, that’s better
http://lihaoyi.github.io/scalatags/
Conclusions
Should I use Scala to replace my ...
JavaScript Probably not.Boilerplate and bugs outweigh type safety benefits.
CSS Nope. Just use Sass like everyone else.
HTML Maybe. Scalatags could be useful as a templating lang, to replace e.g. Scalate