BT

Compile Scala to JavaScript With Scala.js

by Zef Hemel on Jun 20, 2013 |

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.

Hello stranger!

You need to Register an InfoQ account or or login to post comments. But there's so much more behind being registered.

Get the most out of the InfoQ experience.

Tell us what you think

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Email me replies to any of my messages in this thread
Community comments

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Email me replies to any of my messages in this thread

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Email me replies to any of my messages in this thread

Discuss

Educational Content

General Feedback
Bugs
Advertising
Editorial
InfoQ.com and all content copyright © 2006-2014 C4Media Inc. InfoQ.com hosted at Contegix, the best ISP we've ever worked with.
Privacy policy
BT