一、配置
从grunt迁移到gulp后,发现很多功能没有grunt那么酷,但是类似功能也支持,比如雪碧图,功能稍微弱一些,但是也很棒
NPM地址:https://www.npmjs.com/package/gulp-css-spriter/ https://www.npmjs.com/package/grunt-css-sprite
vargulp=require(‘gulp‘), minifyCSS=require(‘gulp-minify-css‘), spriter=require(‘gulp-css-spriter‘);
二、gulp
gulp.task(‘css‘, function(){ var timestamp = +new Date(); return gulp.src(srcPath.css) .pipe(spriter({ // 生成的spriter的位置 ‘spriteSheet‘: ‘./web/images/sprite_‘+timestamp+‘.png‘, // 生成样式文件图片引用地址的路径 // 如下将生产:backgound:url(../images/sprite20324232.png) ‘pathToSpriteSheetFromCSS‘: ‘../images/sprite_‘+timestamp+‘.png‘ })) .pipe(minifyCss()) .pipe(autoprefixer({ browsers:[‘last 2 Chrome versions‘, ‘Safari >0‘, ‘Explorer >0‘, ‘Edge >0‘, ‘Opera >0‘, ‘Firefox >=20‘], cascade:false, remove:false, })) .pipe(gulp.dest(distPath.css));//保存压缩文件到指定的目录下面 });
三、css
.w{width: 266px;height: 78px;background: url(../images/w.png?__spriter) 0 0 no-repeat;} .j{width: 270px;height: 60px;background: url(../images/jd.png?__spriter) 0 0 no-repeat;} .t{width: 290px;height: 100px;background: url(../images/tmall.png) 0 0 no-repeat;}
四、配置
gulp-css-spriter默认会对样式文件里,所有的background/background-image的图片合并,
但实际项目中,我们不是所有的图片都需要合并。
background-image:url(../slice/p1-3.png?__spriter);//有?__spriter后缀的合并
background-image:url(../slice/p-cao1.png);//不合并
修改下面文件可以按需合并。
node_modules\gulp-css-spriter\lib\map-over-styles-and-transform-background-image-declarations.js
48行开始的if-else if代码块中,替换为下面代码:
//background-imagealwayshasaurl且判断url是否有?__spriter后缀
if(transformedDeclaration.property===‘background-image‘&&/\?__spriter/i.test(transformedDeclaration.value)){
transformedDeclaration.value=transformedDeclaration.value.replace(‘?__spriter‘,‘‘);
returncb(transformedDeclaration,declarationIndex,declarations);
}
//Backgroundisashorthandpropertysomakesure`url()`isinthere且判断url是否有?__spriter后缀
elseif(transformedDeclaration.property===‘background‘&&/\?__spriter/i.test(transformedDeclaration.value)){
transformedDeclaration.value=transformedDeclaration.value.replace(‘?__spriter‘,‘‘);
varhasImageValue=spriterUtil.backgroundURLRegex.test(transformedDeclaration.value);
if(hasImageValue){
returncb(transformedDeclaration,declarationIndex,declarations);
}
}
完整图片
没有添加?__spriter不会合并