The best part of ES6 is that you can use it, despite the fact it hasn’t been finished yet.
How can I use ES6 in my web browser?
One of most exciting features of ES6 are built-in modules. Before ES6 we used solutions like CommonJS or RequireJS. By default Babel uses CommonJS modules as a fallback. If you didn’t use any type of packaging and want to use one, you will need to setup one.
Bringing ES6 to Rails
Sprockets 4.x promise to bring ES6 transpiling out of the box. This release doesn’t seem to come up soon, so we need to find some way around.
Using Sprockets with
On babel website we can find link to
sprockets-es6 gem, which enables ES6 transpiling for sprockets. Unfortunately it does not come without problems - the gem requires
sprockets in version
~3.0.0.beta. By default babel converts ES6 modules to CommonJS modules. Two gems providing CommonJS (
sprockets to be in version lower than 3.0.0.
If you decide to go with this method, you just need to put these two files in Gemfile.
gem 'sprockets', '>=3.0.0.beta' gem 'sprockets-es6'
And now run
bundle install. After installation you can write your ES6 code in files with
Using Node.JS with Gulp
Marcin wrote some time ago about unusual approach for asset serving in Rails applications. We can completely remove sprockets and do it on our own with simple Node.js application.
We want to remove any dependencies on Sprockets or any other Ruby gem, when it comes to asset serving. Moreover, using this method, we get faster overall asset compiling than with Sprockets.
With Gulp, we can use
browserify node packages in our asset processing process. It let us to use all ES6 features without any inconvenience. You can see example Gulpfile.js with ES6 transpiling and SASS compiling on gist: Gulpfile.js
There are many more workarounds to get ES6 in Rails environment that doesn’t require discarding Sprockets. Unfortunately none of them are good enough to mention as production-ready. I strongly recommend going with Gulp. It’s simple, powerful and provides native environment to work with assets.
If you don’t want to switch from Sprockets, you can try-out
If you want to receive more articles about Rails and front-end, sign-up for our newsletter below.