Home >Web Front-end >HTML Tutorial >gulp-css-spriter merges sliced images in css code into sprite images_html/css_WEB-ITnose
NPM address: https://www.npmjs.com/package/gulp-css-spriter/
Configure gulpfile .js:
var gulp = require('gulp'),
minifyCSS = require('gulp-minify-css'),
spriter = require('gulp -css-spriter');
gulp.task('css', function() {
var timestamp = new Date();
// Need to automatically merge sprite images Style file
return gulp.src('./src/css/style.css')
.pipe(spriter({
> ) // The location of the generated spriteer
'spriteSheet': '. /dist/images/sprite' timestamp '.png',
/ > 'pathToSpriteSheetFromCSS': '../images/sprite' timestamp '.png'
}))
.pipe(minifyCSS())
// Output path
.pipe(gul p. dest('./dist'));
});
Tips:
gulp-css-spriter defaults to style files , all background/background-image pictures are merged,
But in actual projects, we do not need to merge all pictures.
background-image: url(../slice/p1-3.png?__spriter);//Merge with ?__spriter suffix
background-image: url(. ./slice/p-cao1.png); //Do not merge
Modify the following files to merge as needed.
node_modulesgulp-css-spriterlibmap-over-styles-and-transform-background-image-declarations.js
In the if-else if code block starting at line 48, replace it with the following code:
// background-image always has a url and determine whether the url has?__spriter suffix
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);
}
}
如图:
执行效果: