Backbone.js, Underscore.js, and Sprockets 1.0.x Concatenation

July 19, 2011

Suppose you’re tinkering with Backbone.js, it’s dependency Underscore.js, and being wooed by the song of the single-page javascript app Sirens. Suppose you love the separation of logical files, but really despise adding each individual file to your index.html page. Suppose you stumble upon the Sprockets 1.0.x branch by Sam Stephenson.

If so, then we’ve got a lot in common, friend! Particularly if you happen to run into this error:

`block in interpolate_constants!': couldn't find constant `([\s\S]+?)' in line 756 of ~/d/js/lib/underscore-1.1.7.js (Sprockets::UndefinedConstantError)

Fortunately for us, we aren’t the first ones to run into this problem. It was filed as ticket 23 on the prototype library lighthouse page. Even better, github community member matehat solved this by adding an :interpolate_constants option to the Sprockets::Secretary constructor in smile-inducing commit d73565.

Now, if we have even more in common, you’ve never built a gem from source either. Let’s walk through this together!

  1. gem uninstall sprockets
  2. git clone https://github.com/matehat/sprockets.git
  3. cd sprockets
  4. gem build sprockets.gemspec
  5. gem install sprockets-1.0.2.gem

Holy Toledo that was easy. Special nod to stackoverflow’s dominikh for concisely stating how super easy gem-building is.

And just like that, we can pass a new option into our Sprockets::Secretary constructor to actually create one file, frameworks and all.

before

require 'sprockets'

secretary = Sprockets::Secretary.new(
  :root         => '.',
  :asset_root   => 'bin',
  :load_path    => ['../lib'],
  :source_files => ['src/*.js', 'src/**/*.js']
)
secretary.concatenation.save_to('bin/app.js')

after

require 'sprockets'

secretary = Sprockets::Secretary.new(
  :root         => '.',
  :asset_root   => 'bin',
  :load_path    => ['../lib'],
  :source_files => ['src/*.js', 'src/**/*.js'],
  :interpolate_constants => false  )
secretary.concatenation.save_to('bin/app.js')

Profile picture

Written by @sghill, who works on build, automated change, and continuous integration systems.