gulp-css-spriter 将css代码中的切片图片合并成雪碧图
本篇文章主要介绍了"gulp-css-spriter 将css代码中的切片图片合并成雪碧图",对于HTML教程感兴趣的同学可以参考一下: NPM地址:https://www.npmjs.com/package/gulp-css-spriter/ 配置gulpfile.js: var gulp ...
NPM地址:https://www.npmjs.com/package/gulp-css-spriter/
配置gulpfile.js:
var gulp = require('gulp'),
minifyCSS = require('gulp-minify-css'),
spriter = require('gulp-css-spriter');
gulp.task('css', function() {
var timestamp = +new Date();
//需要自动合并雪碧图的样式文件
return gulp.src('./src/css/style.css')
.pipe(spriter({
// 生成的spriter的位置
'spriteSheet': './dist/images/sprite'+timestamp+'.png',
// 生成样式文件图片引用地址的路径
// 如下将生产:backgound:url(../images/sprite20324232.png)
'pathToSpriteSheetFromCSS': '../images/sprite'+timestamp+'.png'
}))
.pipe(minifyCSS())
//产出路径
.pipe(gulp.dest('./dist'));
});
技巧 :
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-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 将css代码中的切片图片合并成雪碧图,包括了方面的内容,希望对HTML教程有兴趣的朋友有所帮助。
本文网址链接:http://www.codes51.com/article/detail_117947.html