欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

gulp合并图标到一整图插件gulp.spritesmith使用教程

程序员文章站 2022-04-24 17:23:38
概念 spritesmith的作用就是拼接图片并生成样式表,并且还能输出SASS,Stylus,LESS甚至是JSON。github地址:https://github.com...

概念

spritesmith的作用就是拼接图片并生成样式表,并且还能输出SASS,Stylus,LESS甚至是JSON。github地址:https://github.com/twolfson/gulp.spritesmith

Getting Started

1. Install the module with: npm install gulp.spritesmith

var gulp = require('gulp');
var spritesmith = require('gulp.spritesmith');

gulp.task('sprite', function () {
  var spriteData = gulp.src('images/*.png').pipe(spritesmith({
    imgName: 'sprite.png',
    cssName: 'sprite.css'
  }));
  //这里有两个配置imgName,cssName,下面会详细讲解

  return spriteData.pipe(gulp.dest('path/to/output/'));
});

2. Continuing the pipeline

gulp 执行下列脚本,即可生成合并图

var gulp = require('gulp');
var buffer = require('vinyl-buffer');
var csso = require('gulp-csso');
var imagemin = require('gulp-imagemin');
var merge = require('merge-stream');

var spritesmith = require('gulp.spritesmith');

gulp.task('sprite', function () {
  // Generate our spritesheet
  var spriteData = gulp.src('images/*.png').pipe(spritesmith({
    imgName: 'sprite.png',
    cssName: 'sprite.css'
  }));
  //这里有两个配置imgName,cssName,下面会详细讲解

  // Pipe image stream through image optimizer and onto disk
  var imgStream = spriteData.img
    // DEV: We must buffer our stream into a Buffer for `imagemin`
    .pipe(buffer())
    .pipe(imagemin())
    .pipe(gulp.dest('path/to/image/folder/'));

  // Pipe CSS stream through CSS optimizer and onto disk
  var cssStream = spriteData.css
    .pipe(csso())
    .pipe(gulp.dest('path/to/css/folder/'));

  // Return a merged stream to handle both `end` events
  return merge(imgStream, cssStream);
});

3. config

3.1 个性化配置

  const spritesConfig = {
    //源图片,可以用通配符匹配多张图片,也可以使用数组来枚举多张图片
    src: './src/static/slice/**/*.png',
    //image与css的目标路径
    dest: {
      css: './src/static/styles/sprite/',
      image: './src/static/images/sprite/'
    },
    //配置
    options: {
      //合成图名称
      imgName: 'sprite.png',
      //合成图路径及名称
      imgPath: '../../images/sprite/sprite.png',
      //合成图css样式
      cssName: 'sprite.less',
      //合成图里图标间距
      padding: 4,
      //css格式
      cssFormat: "less",
      //css配置
      cssOpts: {
        cssClass: function(item) {
          // If this is a hover sprite, name it as a hover one (e.g. 'home-hover' -> 'home:hover')
          if (item.name.indexOf('-hover') !== -1) {
            return '.icon-' + item.name.replace('-hover', ':hover');
            // Otherwise, use the name as the selector (e.g. 'home' -> 'home')
          } else {
            return '.icon-' + item.name;
          }
        }
      },
      //2倍图片路径
      retinaSrcFilter: ['./src/static/slice/**/*@2x.png'],
      //2倍图片名称
      retinaImgName: 'sprite@2x.png',
      //合成css模型
      cssTemplate:(data)=> {
        // data为对象,保存合成前小图和合成打大图的信息包括小图在大图之中的信息
        let arr = [],
          width = data.spritesheet.px.width,
          height = data.spritesheet.px.height,
          url = data.spritesheet.image;
        data.sprites.forEach(function (sprite) {
          arr.push(
            ".icon-" + sprite.name +
            "{" +
            "background: url('" + url + "') " +
            "no-repeat " +
            sprite.px.offset_x + " " + sprite.px.offset_y + ";" +
            "background-size: " + width + " " + height + ";" +
            "width: " + sprite.px.width + ";" +
            "height: " + sprite.px.height + ";" +
            "}\n"
          )
        });
        return arr.join("");
      }
    }
  }

3.2 使用个性化配置

    const spriteData = gulp.src(spritesConfig.src)
      .pipe(spritesmith(Object.assign({}, spritesConfig.options)));

    const imgStream = spriteData.img
      .pipe(buffer())
      .pipe(gulp.dest(spritesConfig.dest.image))
      .on('end', () => {
        gutil.log(gutil.colors.green("已完成雪碧图合并,雪碧图保存目录:"));
        gutil.log(gutil.colors.yellow(spritesConfig.dest.image));
      });

    const cssStream = spriteData.css
      .pipe(gulp.dest(spritesConfig.dest.css))
      .on('end', () => {
        gutil.log(gutil.colors.green("已生成雪碧图样式,雪碧图样式保存目录:"));
        gutil.log(gutil.colors.yellow(spritesConfig.dest.css));
      });

    return merge(imgStream, cssStream);

插件也提供使用配置handlebars模板文件来创建模型,例如:cssTemplate:”x/xx/handlebars.css”,然后模板文件.hbs

{{#sprites}}
.icon-{{name}}:before {
       display: block;
       background-image: url({{{escaped_image}}});
       background-position: {{px.offset_x}} {{px.offset_y}};
       width: {{px.width}};
       height: {{px.height}};
     }
 {{/sprites}} 

4. use in html

在html中使用就非常简单了,直接使用,不过在css中需要加上

.icon {
    display: inline-block;
}

5. 注意事项

1. 需要合并的图片一定要准备2x图片,并且名字也要以“@2x”结尾,否则会报错。例如:想合并一张weixin.png的图片,那么需要在同目录下准备一张weixin@2x.png的图片,且尺寸都必须为偶数。