Hooray for ES6 modules on Rails Part 1: Getting Started

In my most recent project, I implemented Conway’s Game of Life using ES6 modules + Rails. With the help of Browserify via Browserify Rails, I was able to organize my code with node-flavored modules and compile them with Babelify for use in the browser.

It’s the first app I’ve built using modern javascript, and doing so was rewarding and a good primer for using ES6 with front-end frameworks like React moving forward (I did not use a front-end framework in this project).

Getting started with Browserify via Browserify Rails is super easy. If you don’t already have node installed, you can do so via Homebrew. Once node is installed, follow these directions to get up and running with ES6:

1.) Add “gem browserify-rails” to your gemfile

2.) Run “bundle install” from Rails console

3.) In application.rb, config Browserify to use Babelify to compile ES6

3.) Run “npm init” from Rails console to create a package.json file in Rails root. Add the following dependencies:

4.) Run “npm install browserify browserifyincremental babelify babelpresetes2015 save” from Rails console to install the required packages locally

5.) Start writing ES6 classes and export them for use in other classes (via import).

Example of exported Cell class:

Example of importing Cell class and using its initialize method in World class:

6.) Require all classes/modules in application.js

That’s it. You’re now ready to use modern JS in the browser and feel confident that you are current with the ever-changing JavaScript landscape.

Postscript: If you haven’t built Conway’s Game of Life before, I highly recommend getting started with this fantastic test-driven tutorial. And definitely solve the problems on your own when he gives you a challenge; you will learn a ton more that way and feel good about it. Note that this is a ruby tutorial and the game is displayed via the Gosu gem in the console. The ES6 stuff above is only applicable if you build the game in the browser.

Advertisements

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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s