Ruby on Rails

Analyse compiled asset size in Rails


Recently I had to do some research into the size of the assets Rails generates. This can be a bit hard to see from your browser, so I wrote a small Rake task to analyse the actual files generated by Rails.

First create a new Rake task in lib/tasks/assets.rake:

include ActionView::Helpers::NumberHelper

namespace :assets do
  task analyse: :environment do
    filename = Dir.glob("public/assets/.*sprockets-manifest*.json").first
    manifest = Sprockets::Manifest.new(Rails.env, filename)

    manifest.files.values.each do |file|
      puts "#{file["logical_path"]}: #{number_to_human_size(file['size'])}"
    end
  end
end

Then clean any existing assets, compile new ones and run the new analyse task:

RAILS_ENV=production bundle exec rails assets:clobber assets:precompile assets:analyse

This will output something like this for each asset file:

  • application.css: 25 KB