Create a gist now

Instantly share code, notes, and snippets.

@kaeff /.bowerrc
Last active Dec 15, 2015

How to use Bower with the Asset Pipeline in Rails
{
"directory" : "vendor/assets/components"
}

This is a quick-and-dirty how-to for managing your front-end dependencies with Twitter Bower.

If you order omakase, the chef's suggestion is dropping everything in vendor/assets. But manually snatching up several repos is a tedious and unsustainable approach, and Asset Gems (like jquery-rails) who do that for you aren't available for the vast amount of front-end frameworks.

Twitter Bower is perfectly suited for this use case. Think RubyGems for the front-end. It let's you resolve packages from a various places like its central registry, github, or just a URL. See the Bower Readme for more.

For more rationale behind this, why not look at Better Component Packaging for Rails' Asset Pipeline.

Be sure you have node.js installed and check out the ruby-bower for more information.

In your Gemfile, add

gem 'ruby-bower', group: :assets

Then, run

$ bundle install

Be sure your application's lib/ directory gets loaded

# In config/application.rb
config.autoload_paths += Dir["#{config.root}/lib/**/"]

Now choose where you want to include your Bower dependencies:

// e.g. in app/assets/javascripts/application.js

//= require_bower_dependencies

Finally, you're able to use Bower to manage dependencies. They will be included in your scripts.

$ bower install --save angular

Notice that some components don't declare they dependencies or main files correctly. For these exeptions, you need to require the according file manually. Why not submit a pull request to the library while at it?

// e.g. in app/assets/javascripts/application.js

//= require_bower_dependencies
//= require underscore/underscore

For now, that's it. Follow me on Twitter to be posted on further developments into this interesting subject. Comments heartily apprechiated!

# In config/initializers/
require 'bower_directive'
Rails.application.assets.register_preprocessor 'application/javascript', Bower::DirectiveProcessor
# In lib/
require 'sprockets/directive_processor'
require 'ruby-bower'
class Bower::DirectiveProcessor < Sprockets::DirectiveProcessor
def process_require_bower_dependencies_directive
Bower.new.list(paths: true)[".js"].each do |filename|
context.require_asset Rails.root.join(filename)
end
end
end
@timsly
timsly commented Oct 4, 2013

Is this approach still valid?
Because Bower.new.list(sources: true) return hash with package details, so [".js"] call return nil

@kaeff
Owner
kaeff commented Dec 16, 2013

I think they've changed the API. It's now

Bower.new.list(paths: true)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment