Skip to content

Recipe: rebuild sprite dynamically with watch

Eugene Lazutkin edited this page Mar 18, 2014 · 1 revision

Sometimes, when editing images, we want to see our changes immediately. grunt comes with a plugin that implements this functionality: grunt-contrib-watch. grunt-tight-sprite is fully compatible with this plugin.

Gruntfile.js

This is a sample grunt file:

"use strict";
var iconPath = "tests/icons/";
module.exports = function(grunt) {
  grunt.initConfig({
    tight_sprite: {
      sprite1: {
        options: {
          hide: iconPath
        },
        src:  [iconPath + "*/**/*.{png,jpg,jpeg,gif}"],
        dest: iconPath + "sprite1.png"
      }
    },
    watch: {
      sprite1: {
        files: ["<%= tight_sprite.sprite1.src %>"],
        tasks: ["tight_sprite:sprite1"]
      }
    }
  });
  grunt.loadNpmTasks("grunt-contrib-watch");
  grunt.loadNpmTasks("grunt-tight-sprite");
};

Usage

Just issue a command:

grunt watch

Now, every time an image is changed, a sprite will be re-generated.

Obviously, we can add more targets for watch and regenerate other relevant pieces (if any) like generate CSS using a CSS preprocessor, lint JS files, generate JS from Coffee files, and so on. The only practical limit for adding more targets is a regeneration speed of added tasks.

Clone this wiki locally