当前位置:Gxlcms > html代码 > gulp-css-spriter将css代码中的切片图片合并成雪碧图_html/css_WEB-ITnose

gulp-css-spriter将css代码中的切片图片合并成雪碧图_html/css_WEB-ITnose

时间:2021-07-01 10:21:17 帮助过:36人阅读

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);
}
}

如图:

执行效果:

人气教程排行