Skip to content

Recipe: rebuild sprite on demand with newer

Eugene Lazutkin edited this page Oct 9, 2015 · 2 revisions

In most cases a sprite should be generated once, and updated only when one of source images was updated. Keeping track of it is a tedious task, and in the *nix world there are several utilities for that. The most used is the venerable make. There is a grunt plugin that implements this functionality: grunt-newer. 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"
      }
    }
  });
  grunt.loadNpmTasks("grunt-tight-sprite");
  grunt.loadNpmTasks("grunt-newer");
  grunt.registerTask("sprite", "newer:tight_sprite");
};

Usage

Just issue a command:

grunt sprite

If we have a fresh sprite image, it will not be regenerated saving us time. If one or more source images were updated, new sprite will be re-generated.

Hint: when using time-based commands, make sure that a clock of your computer is correctly set. If you have collaborators, make sure they set their clock correctly too. Otherwise grunt-newer may fail due to incorrect timestamps.