Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using RequireJS with a Rails 3.1 app

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!

like image 600
John Whitley Avatar asked Oct 27 '11 19:10

John Whitley


1 Answers

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

like image 132
John Whitley Avatar answered Oct 17 '22 21:10

John Whitley