Yeoman: Scala in the browser

Recently I had made another small Yeoman generator, this time for Scala.js. The orignal code was based on Scala.js TodoMVC example.

The generator scaffolds a fullstack project entirely written in Scala language. The backend uses Play Framework, the frontend – Scala.js Angular. As you may expect the Scala.js Angular defines the bindings to AngularJS and whole web application is being compiled into JavaScript code.

Let’s see this in practice:


$ npm i -g generator-scalajs-angular

Create a new directory for your project and run the Yeoman for scaffolding your project:

 
$ mkdir scalajs-angular-app && cd $_
$ yo scalajs-angular 

Note: The first run will execute sbt compile which might take a long time due to download all of the project dependencies.

The directory structure looks as fallows:

.
├── build.sbt
├── project
│   ├── Build.scala
│   ├── build.properties
│   ├── plugins.sbt
├── scalajs
│   ├── src
└── scalajvm
    ├── app
    ├── conf
    ├── public

Where scalajvm is a Play backend, it servers the static content as well implements basic logic to persist the data in embedded H2 database.

In contrary scalajs directory contains the files that are compiled into JavaScript. How it looks like? More or less as regular Scala code:

@JSExport
object TodoApp extends JSApp {

  override def main() {
    val module = Angular.module("todomvc")

    module
      .controller[TodoCtrl]
      .directive[TodoItemDirective]
      .directive[EscapeDirective]
      .directive[FocusDirective]
      .filter[StatusFilter]
      .factory[TaskServiceFactory]
  }
}

There are two important parts here, first is the JSExport annotation, that indicates that this class should be exported into JavaScript. The second one is JSApp. Extending this class indicates that this is the entry point of the application and the main method should be executed when the application get’s loaded by the browser.

Let’s run this application:


$ sbt run

After the server starts open the http://localhost:9000 in your browser. You see similar page.

Scala Angular Screen

What is interesting is the fact that you can in fact debug your Scala code in the browser, just open Chrome Development tools or Firebug and you can step over your the application line by line. The Scala.js will automaticly generated the source map for your project.

Scalajs debuging

 

You can find more details on the project page:

https://www.npmjs.com/package/generator-scalajs-angular

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s