Pete Hamilton

AngularJS + Rails with Bower

I really don’t like committing library code to my repos.

For a project I’m hacking around on this weekend I’m using AngularJS, Normalize.css and a bunch of other front end JS and CSS libraries. Bower seemed perfect to organise all of this but there wasn’t too much information out there on how to combine it with rails.

So, here’s my quick guide to getting set up with front end vendor assets in rails with Bower.

1. You’ll need to have bower installed:

sudo npm install -g bower

2. Tell Bower where to put the components

In the root of your project, create a .bowerrc file to tell bower where to install the components.

{
  "directory": "vendor/assets/components"
}

3. Tell Bower which components to install

Also create a bower.json file to tell bower which components you’d like to install. See the full registry list here

This was mine:

// bower.json

{
  "dependencies": {
    "angular-activerecord": "*",
    "angular-all-unstable": "*",
    "normalize-css": "*"
  }
}

4. Tell Rails to include components in the assets pipeline:

Add vendor assets components to the asset pipeline

# config/application.rb

# Add Bower components to assets pipeline
config.assets.paths << Rails.root.join('vendor', 'assets', 'components')

5. Add your libraries to app/assets/application.js

Assets are included by package/jsfile. So, for example, to include angular and angular-resource in my rails app, I added:

// app/assets/javascripts/application.js

//= require angular-all-unstable/angular
//= require angular-all-unstable/angular-resource

See asset pipeline docs for more details on how/why this works.

6. Ignore components in source control

Finally, we don’t want to commit any of these libraries to our repository so in your .gitignore file (or equivalent if another vcs) add:

# Ignore Bower Assets
/vendor/assets/components

And that’s it, super simple, but worth remembering next time you’re tempted to paste JS or CSS libraries into your project

References: