Sign Up for Free

RunKit +

Try any Node.js package right in your browser

This is a playground to test code. It runs a full Node.js environment and already has all of npm’s 400,000 packages pre-installed, including gulp-sprite-generator with all npm packages installed. Try it out:

var gulpSpriteGenerator = require("gulp-sprite-generator")

This service is provided by RunKit and is not affiliated with npm, Inc or the package authors.

gulp-sprite-generator v0.2.3

Plugin that generate sprites from your stylesheets (using spritesmith) and then updates the references.

gulp-sprite-generator

npm version Build Status

Generate sprites from stylesheets.

Plugin that generate sprites from your stylesheets (using spritesmith) and then updates image references.

Getting started

If you haven't used gulp before, be sure to check out the Getting Started guide.

Install with npm

npm install --save-dev gulp-sprite-generator

Overview

Sprite generator is a gulp task, which accepts options object and returns two streams for style and image piping.

Here quick example of simple way usage:

var gulp = require('gulp');
var sprite = require('gulp-sprite-generator');

gulp.task('sprites', function() {
    var spriteOutput;

    spriteOutput = gulp.src("./src/css/*.css")
        .pipe(sprite({
            baseUrl:         "./src/image",
            spriteSheetName: "sprite.png",
            spriteSheetPath: "/dist/image"
        });

    spriteOutput.css.pipe(gulp.dest("./dist/css"));
    spriteOutput.img.pipe(gulp.dest("./dist/image"));
});

Of course you may need to have more flexible configuration for spriting. And this plugin could give you something more!

Options

Sprite generator options is an object, that mix spritesmith options and plugin specific options.

Spritesmith parameters (all is optional):

PropertyNecessaryTypePlugin default value
[engine]noString"pngsmith"
[algorithm]noString"top-down"
[padding]noNumber0
[engineOpts]noObject{}
[exportOpts]noObject{}

More detailed explanation you can find on the official page of spritesmith.

Plugin options are:

PropertyNecessaryTypePlugin default value
spriteSheetNameyesStringnull
[spriteSheetPath]noStringnull
[styleSheetName]npStringnull
[baseUrl]noString"./"
[retina]noBooleantrue
[filter]noFunction[][]
[groupBy]noFunction[][]
[accumulate]noBooleanfalse
[verbose]noBooleanfalse

More detailed explanation is below.

options.spriteSheetName

Type: String Default value: null

The one and last necessary parameter. Defines which base will have the name of the output sprite. Base means that if you will group your sprites by some criteria, name will change.

options.spriteSheetPath

Type: String Default value: null

Can define relative path of references in the output stylesheet.

options.styleSheetName

Type: String Default value: null

Defines the name of the output stylesheet.

options.baseUrl

Type: String Default value: ./

Defines where to find relatively defined image references in the input stylesheet.

options.retina

Type: Boolean Default value: true

Defines whether or not to search for retina mark in the filename. If true then it will look for @{number}x syntax. For example: image@2x.png.

options.filter

Type: Function[], Function Default value: []

Defines which filters apply to images found in the input stylesheet. Each filer called with image object, explained below. Each filter must return Boolean or thenable Promise, that will be resolved with Boolean. Each filter applies in series.

options.groupBy

Type: Function[], Function Default value: []

Defines logic of how to group images found in the input stylesheet. Each grouper called with image object, explained below. Each filter must return String|Null or thenable Promise, that will be resolved with String|Null. Each grouper applies in series.

options.accumulate

Type: Boolean Default value: false

Tells sprite-generator to accumulate images from multiple stylesheets. This mean, that images, found in stylesheet A.css and B.css will be accumulated and grouped in common sprite.

Note, that if options.accumulate == true then options.styleSheetName will not be used.

options.verbose

Type: Boolean Default value: false

Filtering and grouping

Sprite generator can filter and group images from the input stylesheet.

Built in filters:

  • based on meta skip boolean flag;
  • based on fs.exists method to check, whether file exists or not.

Built in groupers:

  • based on @2x image naming syntax, will produce sprite.@{number}x.png naming. (@{number}x image group).

You can of course define your own filters or groupers. It will all based on main argument - the image object.

The Image object

Every filter or grouper is called with image object, that have these properties:

PropertyTypeExplanation
replacementStringString, found by pattern in the input stylesheet
urlStringUrl for image fount in the input stylesheet
pathStringResolved path for the image
groupString[]List of string, representing groups of image
isRetinaBooleanBoolean flag of retina image (@2x syntax)
retinaRatioNumberRatio of retina image (@2x, @3x => 2, 3)
metaObjectObject of meta properties, defined in doc block (will explain below).

Doc block meta properties

You can also define some properties for the filters and groupers in doc block via this syntax:

{css definition} /* @meta {valid json} */

Example:


.my_class {
    background-image: url("/images/my.png"); /* @meta {"sprite": {"skip": true}} */
}

Important! Only object in sprite property of meta will be available in image object for filters and groupers.

Flexible example


var gulp   = require('gulp'),
    sprite = require('gulp-sprite-generator'),
    Q      = require('q'),
    sizeOf = require('image-size');

gulp.task('sprites', function() {
    var spriteOutput;

    spriteOutput = gulp.src("./src/css/*.css")
        .pipe(sprite({
            baseUrl:         "./",
            spriteSheetName: "sprite.png",
            spriteSheetPath: "/dist/image",
            styleSheetName:  "stylesheet.css",

            filter: [
                // this is a copy of built in filter of meta skip
                // do not forget to set it up in your stylesheets using doc block /* */
                function(image) {
                    return !image.meta.skip;
                }
            ],

            groupBy: [
                // group images by width
                // useful when building background repeatable sprites
                function(image) {
                    var deferred = Q.defer();

                    sizeOf(image.path, function(err, size) {
                        deferred.resolve(size.width.toString());
                    });

                    return deferred.promise;
                }
            ]
        });

    spriteOutput.css.pipe(gulp.dest("./dist/css"));
    spriteOutput.img.pipe(gulp.dest("./dist/image"));
});

License

MIT © Sergey Kamardin

Metadata

RunKit is a free, in-browser JavaScript dev environment for prototyping Node.js code, with every npm package installed. Sign up to share your code.
Sign Up for Free