Fork me on GitHub

gulp-css-spriter 雪碧图合并

相信做前端的同学都做过这样的事情,为优化图片,减少请求会把拿到切好的图标图片,通过ps(或者其他工具)把图片合并到一张图里面,再通过css定位把对于的样式写出来引用的html里面。gulp-css-spriter 让这一切别的更简单了。

本文只介绍gulp-css-spriter的使用,其它相关文章请自行Google了解^_^。

  第一步: 

npm install gulp-css-spriter

  第二步:(主要就看三行代码即可,注意:合并之前的html页面里面的标签宽高必须要和背景图宽高一样,且不能用背景定位,否则会出现问题!!!)

gulp.task('html', ['styles', 'scripts'], () => {
  var timestamp = +new Date();//定义一个时间戳
  return gulp.src('app/*.html')
    .pipe($.useref({searchPath: ['.tmp', 'app', '.']}))
    .pipe($.if('*.js', $.uglify()))
    .pipe($.if('*.css', $.cssnano({safe: true, autoprefixer: false})))
    .pipe($.if('*.css', $.cssSpriter({
            // The path and file name of where we will save the sprite sheet
            'spriteSheet': './dist/images/sprite'+timestamp+'.png', //这是雪碧图自动合成的图。 很重要
            // Because we don't know where you will end up saving the CSS file at this point in the pipe,
            // we need a litle help identifying where it will be.
            'pathToSpriteSheetFromCSS': '../images/sprite'+timestamp+'.png' //这是在css引用的图片路径,很重要
        })))
    // .pipe($.if('*.html', $.htmlmin({collapseWhitespace: true})))
    .pipe($.if('*.html', $.htmlmin({collapseWhitespace: false})))
    .pipe(gulp.dest('dist'));
});

  OK,至此你应该已经完成了,但是你可能发现css里面的backgroundimg都被合并了,那就对了gulp-css-spriter默认会对样式文件里,所有的background/background-image的图片合并,但实际项目中,我们不是所有的图片都需要合并。

background-image: url(../images/icon-3.png?__sprite);//有?__sprite后缀的合并
background-image: url(../images/pics1.png); //不合并 

  修改一下文件可以按需合并。( node_modules/gulp-css-spriter/lib/map-over-styles-and-transform-background-image-declarations.js  下载地址:点击下载) , 48行开始的if-else if代码块中,替换为下面代码:

                  // background-image always has a url 且判断url是否有?__spriter后缀

                if(transformedDeclaration.property === 'background-image' && /\?__spriter/i.test(transformedDeclaration.value)) {

                    transformedDeclaration.value = transformedDeclaration.value.replace('?__spriter','');
                    return cb(transformedDeclaration, declarationIndex, declarations);
                }
                // Background is a shorthand property so make sure `url()` is in there 且判断url是否有?__spriter后缀
                else if(transformedDeclaration.property === 'background' && /\?__spriter/i.test(transformedDeclaration.value)) {

                    transformedDeclaration.value = transformedDeclaration.value.replace('?__spriter','');
                    var hasImageValue = spriterUtil.backgroundURLRegex.test(transformedDeclaration.value);

                    if(hasImageValue) {
                        return cb(transformedDeclaration, declarationIndex, declarations);
                    }
                }

  

本文标题:gulp-css-spriter 雪碧图合并

原创作者:Jiao Shou

发布时间:2016年10月13日 - 09:20

最后更新:2016年10月13日 - 21:09

原始链接:http://www.cnblogs.com/jiaoshou/p/5955184.html

许可协议:转载本篇文章时请务必以超链接形式标明文章原文链接和作者信息。

扫描二维码,分享此文章

posted @ 2016-10-13 09:20  较瘦  阅读(1313)  评论(0编辑  收藏  举报
知识点文章整理