How do I minify CSS in Rails 4?
Solution 1
I was having the same problem in my production environment, where I couldn't get the CSS to minify upon deploying to Heroku. After turning on compression with the following:
production.rb
config.assets.css_compressor = :sass
Gemfile
gem 'sass-rails', '~> 4.0.0'
I managed to get it to minify by updating the assets version:
production.rb
config.assets.version = '1.1' # was '1.0'
Doing a few tests afterwards, I found that updating the source CSS/SASS had the same effect. So try updating your stylesheets (as opposed to only the config), which should "kickstart" the minification process when Heroku precompiles your assets after you push, without needing to update the assets version.
Solution 2
Precompile
You'll need to precompile the assets
Rails minifies your assets if you precompile them. This is only for production, but means you're able to use files such as application.js
and application.css
with minified code
Try this:
$ rake assets:precompile RAILS_ENV=production
$ git add .
$ git commit -a -m "Precompiled Assets"
$ git push heroku master
This will precompile (& minify) your assets, allowing you to use the compiled files in production
Chloe
Updated on June 11, 2022Comments
-
Chloe almost 2 years
I tried the following, however I look at the CSS source and it does not minify! I restarted the server several dozen times. I turned off cache in the browser. I also tried the 'yui-compressor' gem.
config/environments/development.rb
config.assets.debug = false config.assets.css_compressor = :sass config.assets.compile = true
Gemfile
group :assets do # Add any compass extensions here # Use SCSS for stylesheets gem 'sass-rails', '~> 4.0.0'
Reference
http://edgeguides.rubyonrails.org/asset_pipeline.html#customizing-the-pipeline
Version
WEBrick 1.3.1, ruby 2.0.0 (2013-06-27) [i386-mingw32], Rails 4.0.3
-
Chloe about 10 yearsDoesn't Heroku already compile the assets automatically?
Preparing app for Rails asset pipeline Running: rake assets:precompile Asset precompilation completed (3.64s) Cleaning assets Running: rake assets:clean
. How do I view the minified version in development, to test that everything is working? The JS is minified. Is there a way to minify the CSS without having to remember to check it into GIT each time, and clutter up the file system every time there is a deploy? -
cimmanon over 9 yearsWhat does this have to do with the question?
-
Dan Kohn over 9 yearsI spent several hours debugging a situation where the lack of the slash prevented fingerprinting from working correctly. I wanted to let others know why CSS would minify without fingerprinting working.
-
Benjamin over 8 yearsBy the author's own admission, this method should not be used, as it adds significant overhead to every.single.request.