gulp-css-spriter 雪碧图合并

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

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

  第一步: html

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的图片合并,但实际项目中,咱们不是全部的图片都须要合并。java

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代码块中,替换为下面代码:node

                  // 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 雪碧图合并npm

原创做者:Jiao Shougulp

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

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

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

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

扫描二维码,分享此文章

相关文章
相关标签/搜索