twolfson / gulp.spritesmith

Convert a set of images into a spritesheet and CSS variables via gulp
The Unlicense
1.07k stars 81 forks source link

One sprite, multiple CSS files? #123

Closed Jos512 closed 7 years ago

Jos512 commented 7 years ago

I struggle with the following: for my sites, I use different CSS files so that redundant CSS rules are kept to a minimum (to aid page speed).

But gulp.spritesmith 'forces' me to use one CSS file for a sprite. When deploying, I'll then have to merge that CSS file into each individual CSS file, giving a lot of unnecessary rules.

Is there perhaps a way to generate one sprite but different CSS files?

My failed attempt for this is the following:

// Gulp task for generating the CSS image sprite for posts and pages
gulp.task('sprites', function() {

    // Create the CSS and sprite
    var postSprite = gulp.src('public/static/icons/sprites-post/*.png')
        .pipe(spritesmith({
            imgName: 'post-sprite.png',
            cssName: 'post-sprite.css'
        }));

    var pageSprite = gulp.src('public/static/icons/sprites-page/*.png')
        .pipe(spritesmith({
            imgName: 'page-sprite.png',
            cssName: 'page-sprite.css'
        }));

    // Output the CSS
    var postCSSstream = postSprite.css
        .pipe(gulp.dest('deploy/static/css-sprite-test/'));
    var pageCSSstream = pageSprite.css
        .pipe(gulp.dest('deploy/static/css-sprite-test/'));

    // Concatenate the image stream
    var imgStream = merge(postSprite.img, pageSprite.img)
        .pipe(buffer())
        .pipe(concat('sprite-combined.png'))
        .pipe(gulp.dest('deploy/static/css-sprite-test/'));

    return merge(postCSSstream, pageCSSstream, imgStream);
});

Any insights appreciated!

twolfson commented 7 years ago

We built non-CSS templates that expose variables and mixins to support this kind of behavior. Here's an example with SCSS:

gulpfile.js:

gulp.task('build-sprite', function buildSpriteFn () {
    // Generate our common spritesheet and SCSS variables
    return gulp.src('public/static/icons/sprites/*.png')
        .pipe(spritesmith({
            imgName: 'sprite.png',
            cssName: 'sprite.scss' // Note the `.scss` extension
        }))
        .pipe(gulp.dest('deploy/static/css-sprite-test/'));
});

gulp.task('build-css', function buildCssFn () {
    // Generate our multiple stylesheets
    return gulp.src('public/static/*.scss') // Load post.scss and page.scss
        .pipe(gulp.dest('deploy/static/css-sprite-test/')); // Outputs post.css and page.css
});

post.scss and page.css:

@import "../../deploy/static/css-sprite-test/sprite.scss";

@include sprites($spritesheet-sprites);

// More post.css/page.css
Jos512 commented 7 years ago

Thanks for your quick comment and example, much appreciated!