Minify CSS & Javascript on the fly with Guard

My new favorite tool for compressing my Javascript and CSS on the fly as well as compiling my SASS is called Guard. Guard keeps track of changes in your local file system and performs actions when it detects a change.

Guard is written in Ruby and at this moment more than 190 plugins have been written for it. To compile SASS and minify Javascript and CSS you need the guard-concat, guard-jammit, guard-sass and guard-uglify plugins.

gem install guard
gem install guard-concat
gem install guard-jammit
gem install guard-sass
gem install guard-uglify

Next create a guard configuration file (Guardfile) in your project root and set up and configure it according your needs:

guard init

Here a example configuration file for automatic SASS compilation and CSS/Javascript compression:

guard :sass, :input => "style/scss", :output => "style/css"

guard :jammit, :config_path => "assets.yml", :output_folder => "." do
  watch(%r{(?:style|javascript)(/.+)\.(?:css|js)}) { |m| m[0] unless m[1] =~ /\/\./ }

The asset list for Jammit:

gzip_assets: off
javascript_compressor: uglifier

    - style/css/some-library-style-file.css
    - style/css/style.css

    - public/js/some-library.js
    - javascript/script.js

Once you are done setting up the config files you need to start Guard in your project root:

dev@dev:/src/example$ guard
06:04:54 - INFO - Guard uses TerminalTitle to send notifications.
06:04:54 - INFO - Using Jammit version 0.6.6
06:04:54 - INFO - Jammit successfully packaged the assets.

One thing to consider is that if your SASS compilation fails because of invalid syntax the entire compilation and minification process will stop and you will get a dated version of your CSS/JS served in your browser. If your latest changes are not reflected in your browser after a refresh its a good idea to have a look at the Guard log to see if the compilation failed.

Minify CSS & Javascript on the fly with Guard