標籤:
相信做前端的同學都做過這樣的事情,為最佳化圖片,減少請求會把拿到切好的表徵圖圖片,通過ps(或者其他工具)把圖片合并到一張圖裡面,再通過css定位把對於的樣式寫出來引用的html裡面。gulp-css-spriter 讓這一切別的更簡單了。
本文只介紹gulp-css-spriter的使用,其它相關文章請自行Google瞭解^_^。
第一步:
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的圖片合并,但實際項目中,我們不是所有的圖片都需要合并。
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代碼塊中,替換為下面代碼:
// 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 雪碧圖合并