gulp.spritesmith使用总结

来源:互联网 发布:手机区域截图软件 编辑:程序博客网 时间:2024/06/05 10:32

gulp.spritesmithnpm地址: https://www.npmjs.com/package/gulp.spritesmith

我使用的版本: ^6.7.0

合并雪碧图, 假定需要合并的小图为CONFIG.src + '/img/slice/*.png',
具体情况自己配置即可.

gulp.task('sprite', function() {  var spriteData = gulp.src(CONFIG.src + '/img/slice/*.png')    .pipe(plugins.spritesmith({      imgName: 'sprite.png', // 生成的雪碧图的路径      cssName: '../less/_sprite.less', // 生成less文件, 方便引用      imgPath: '../img/sprite.png', // 手动指定路径, 会直接出现在background属性的值中      padding: 4, // 小图之间的间距, 防止重叠      cssFormat: 'css', // less文件内容以css的格式输出      // 这个选项用来重新命名生成的类名      // 如果不配置, 会自动添加 icon- 前缀      // 参见https://github.com/Otouto/gulp-spritesmith/issues/10      // cssOpts: {      //   cssSelector: function(sprite) {      //     return '.i-' + sprite.name;      //   }      // },      // 手动指定模板      cssTemplate: (data) => {        // data为对象,保存合成前小图和合成打大图的信息包括小图在大图之中的信息        let arr = [],          width = data.spritesheet.px.width,          height = data.spritesheet.px.height,          url = data.spritesheet.image;        arr.push(`.icon {  display: inline-block;  vertical-align: middle;  background: url("${url}") no-repeat;}`);        data.sprites.forEach(function(sprite) {          arr.push(`.i-${sprite.name} {  width: ${sprite.px.width};  height: ${sprite.px.height};  background-position: ${sprite.px.offset_x} ${sprite.px.offset_y};  background-size: ${sprite.px.width} ${sprite.px.height};}`);        });        return arr.join('');      }    }));  return spriteData.pipe(gulp.dest(CONFIG.dist + '/img'));});

事实上, 有了cssTemplate这个配置项, 想怎么生成都可以, 看实际需要.

欢迎补充指正!