本文的样式预处理使用的是stylus 若是需要用到其它类型的预处理器,可对下面的代码进行修改
若是想对雪碧图的生成原理及参数有更深刻的了解请移步css
const spritesmith = require("gulp.spritesmith"); gulp.task("sprite", () => { var spriteData = gulp.src("./src/styles/img/icons/*.png").pipe( spritesmith({ // 生成雪碧图的位置以及名称 imgName: "img/sprite.png", // 生成的雪碧图的样式位置 cssName: "__sprite.styl", // 雪碧图中图片与图片的padding padding: 5, // 雪碧图中图片的排列方式 algorithm: "binary-tree", // 这里是生成__sprite.styl的模板文件,需要针对不图的样式预处理器进行我的的修改 cssTemplate(data) { var fuc = []; var perSprite = []; var shared = "sicon() { background-image: url(I); display: inline-block; vertical-align: middle; position: relative; top: -2px; background-size: Wpx Hpx; }" .replace("I", data.spritesheet.image) .replace("W", data.spritesheet.width) .replace("H", data.spritesheet.height); Array.prototype.forEach.call(data.sprites, function(sprite) { fuc.push( "sicon-N() { width: Wpx; height: Hpx; background-position: Xpx Ypx; }" .replace(/N/g, sprite.name) .replace("W", sprite.width) .replace("H", sprite.height) .replace("X", sprite.offset_x) .replace("Y", sprite.offset_y) ); perSprite.push( "\t.sicon-N {\t\n\t\tsicon-N()\t\n\t}".replace(/N/g, sprite.name) ); }); return ( shared + '\n' + fuc.join("\n") + "\nsprites(){\n\t" + ".sicon{\n\t\tsicon()\n\t}" + "\n" + perSprite.join("\n") + "\n}" ); } }) ); return spriteData.pipe(gulp.dest("./src/styles")); });
这段代码会在指定位置生成__sprite.styl的函数集合文件git
sicon() { background-image: url(img/sprite.png); display: inline-block; vertical-align: middle; position: relative; top: -2px; background-size: 286px 256px; } sicon-checkbox-checked-focus() { width: 17px; height: 17px; background-position: -22px -220px; } sprites(){ .sicon{ sicon() } .sicon-checkbox-checked-focus { sicon-checkbox-checked-focus() } }
能够在入口处调用sprites()函数,生成全局样式github
调用对应图片的函数以及公用函数便可
以下:gulp
.xxx{ sicon() sicon-checkbox-checked-focus() }
但愿对你们有用,平时不太爱写文章。能写上来的都是比较实用的东西函数