The UrBlog

John's Ramblings about Software Development

Using ECMAScript 6 in Grails

I’ve been writing a lot of JavaScript lately. I like to apply the same engineering principles to my JavaScript code that I apply to any other language so I break my code up into separate clases and modules, each in their own file. If I’m writing code using Node, I use browserify or RequireJS to help manage this. On Grails projects I used the resource plugin in the past. Lately I’ve started using the asset-pipeline plugin.

I also use JavaScript constructor functions often, especially when using AngularJS. While it’s a bit clunky to code prototypes this way, browser VMs optimize for that pattern and Angular uses it often.

I’ve been interested in using ECMAScript 6. I like how it simplifies creating prototypes (i.e. the class keyword) and the built in module support. I found a tool called Babel that translates ES6 to readable ES5 code that runs in the browser. It’s easy to plugin into browserify in a Node project. I wanted to start using it in Grails so I created a new asset-pipeline plugin called es6to5-asset-pipeline. (It’s called es6to5 because when I started it, babel was called 6to5).

Usage is simple:

  1. Include the asset-pipeline and es6to5-asset-pipeline plugins in your project
  2. Name your JavaScript files with the extension .es6

The plugin will run each file thru babel, wrap the results in an IIFE and convert the CommonJS style requires and exports into something that will work in the browser.

One of the goals I was able to accomplish was reading the ES6 import lines to figure out what files to require before processing the current file. The asset-pipeline needs the following at the top of your JavaScript file to tell it what files this file depends on:

//= require app/controller/homeCtrl.js

I was able to get my plugin to process the import statements; so instead of this ES6 code:

//= require app/controller/homeCtrl.es6
import HomeCtrl from /app/controller/HomeCtrl.es6

You can leave out the require and avoid the duplication:

import HomeCtrl from /app/controller/HomeCtrl.es6

There is more documentation available on github. Please give it a try and let me know what you think. So far I’ve only used it on a few small personal projects so I’d love to get some folks testing it out.