BT

Facilitating the Spread of Knowledge and Innovation in Professional Software Development

Write for InfoQ

Topics

Choose your language

InfoQ Homepage News Compile Scala to JavaScript With Scala.js

Compile Scala to JavaScript With Scala.js

This item in japanese

Lire ce contenu en français

At the Scala Day last week, Sébastien Doeraene presented Scala.js, a Scala to JavaScript compiler. The compiler supports the full Scala language allowing its users to build web applications front to back in Scala and potentially reuse code between the server and the client.

Scala code written for Scala.js can interact with existing JavaScript code either in a dynamically typed manner, or in a statically typed manner. The former is more flexible: access is provided to the global (window) object and arbitrary properties can be accessed and method called. However, this does not leverage the statically typed nature of Scala. Alternatively, typed signatures of JavaScript libraries can be provided. For instance for jQuery:

These types are used by the compiler to do type checking and to provide code completion in IDEs. Type signature for existing libraries still have to be written by hand, but Scala.js' author is investigating if TypeScript's signatures can be used to automatically generate these for all libraries that TypeScript currently has signatures for. Another issue with Scala.js is that Scala standard library is 16MB of JS after being minimized with the Google Closure compiler. Decreasing this is size is future work

.Here's an example of using jQuery from Scala.js, the example attaches an on-click handler to a button with id "button", and once clicked appends a paragraph tag to a div with id "pane":

jQuery("#button").click { () =>
  val paragraph = jQuery("<p>").html("Hello World!")
  jQuery("div#pane").append(paragraph)
}

It is also possible to call Scala generated code from JavaScript. The compiler generates source maps for compiled code, so that stack traces refer to locations in the original Scala code rather than the generated JavaScript.

The Scala.js compiler is available on github and distributed under the Scala license.

Rate this Article

Adoption
Style

BT