gulp-css-spriter 雪碧图合并
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了gulp-css-spriter 雪碧图合并,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2406字,纯文字阅读大概需要4分钟。
内容图文
相信做前端的同学都做过这样的事情,为优化图片,减少请求会把拿到切好的图标图片,通过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); } }
原文:http://www.cnblogs.com/jiaoshou/p/5955184.html
内容总结
以上是互联网集市为您收集整理的gulp-css-spriter 雪碧图合并全部内容,希望文章能够帮你解决gulp-css-spriter 雪碧图合并所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。