jenssegers

Using Guard to manage assets Written by Jens Segers on 2013-11-10 09:55:58

I have been using jasonlewis/basset for quite a while to manage my assets in Laravel projects. It is definitely not the most optimal/performant solution out there, but it did the job. However, when the project was abandoned a few days ago, I started looking for something new. So, what do I want?

When I started looking around I found Grunt, which seems to be very a popular JavaScript task runner that can do the stuff I want it to do. But man, it was not easy to use at all. It is built on top of Node.js and it's package manager NPM, it requires 2 configuration files and installs dependencies in a folder called node_modules. There is probably a work-around to avoid the modules folder, but the whole tool felt too bloated and "advanced" for the simple tasks I need it to do.

Then I found Guard, which basically monitors your filesystem and fires events for plugins to respond to. It is built on top of Ruby, which is available on OSX right out of the box, and does not require a lot configuration at all.

The only thing I had to do to install Guard and the plugins I needed was:

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

To use guard in a Laravel (or other) project execute:

guard init

This will create a new Guardfile that is used to configure Guard. The Guardfile will contain some default tasks for the installed plugins as an example. For my project I created the following folder structure, inspired by JeffreyWay/Laravel-Guard:

A simple Guard file for this folder structure could look like this:

#--------------------------------------------------------------------------
# Sass
#--------------------------------------------------------------------------

guard 'sass',
    :style => :compressed,
    :input => 'app/assets/sass',
    :output => 'public/css'

#--------------------------------------------------------------------------
# Javascript
#--------------------------------------------------------------------------

guard :concat,
    type: 'js',
    files: %w(jquery script),
    input_dir: 'app/assets/js',
    output: 'public/js/all'

guard 'uglify', :destination_file => 'public/js/all.js' do
    watch (%r{public/js/all.js})
end

The sass part will compile all sass files to their corresponding css file in the public folder. The javascript part will concatenate jquery.js and script.js to all.js in the public folder and minify/uglify that file.

Then, to make sure Guard is watching your files execute:

guard

And that's it. Easy and straightforward.

2 Comments

Vinay Aggarwal, 4 months ago

Good post. Guard code is very neat and require lesser configuration

C├ędric Verstraeten, 5 months ago

nice one :)

Your email address will not be displayed