Using RequireJS with a Rails 3.1 app

John Whitley picture John Whitley · Oct 27, 2011 · Viewed 7.9k times · Source

Question

If you've used RequireJS with a Rails 3 (esp 3.1) app, how is that working for you? Any configuration tricks or other gotchas that I need to watch out for?

Background

I'm contemplating using RequireJS over the Sprockets-based Asset Pipeline in Rails 3.1, specifically for JavaScript code. I have two motivators for this choice:

  • I want to leverage RequireJS' module management for my JS client-side code.
  • I'd like a precompilation system that can follow my JS library code into other contexts. To my surprise, the Asset Pipeline precompiler is a baked-in part of Rails, not a part of Sprockets itself.

All feedback appreciated, thanks!

Answer

John Whitley picture John Whitley · Dec 6, 2011

For posterity, here's where I've come to on this question:

  • RequireJS provides an implementation of the Asynchronous Module Definition API. RequireJS' Why AMD? page lays out the case as to why you'd want to use this.

  • Sprockets and the Rails 3 Asset Pipeline allow for simple structuring of JavaScript/CoffeeScript code, but don't provide any true module support. For example, there's no namespace control whatsoever in Sprockets.

  • jQuery (as of 1.7), Underscore, Dojo and numerous other major libraries have implemented AMD support. Several other major JS libraries seem to have AMD support on the near-term horizion (e.g. Backbone.js).

It's certainly possible to create a Rails app that integrates RequireJS. To simplify that process, I've created the requirejs-rails gem on github, with straightforward configuration and Asset Pipeline-aware precompilation for AMD-based code via r.js. The current release is available via:

gem install requirejs-rails