|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +const gulpif = require('gulp-if'); |
| 4 | +const join = require('path').join; |
| 5 | +const del = require('del'); |
| 6 | +const spritesmith = require('gulp.spritesmith'); |
| 7 | +const buffer = require('vinyl-buffer'); |
| 8 | +const imagemin = require('gulp-imagemin'); |
| 9 | +const merge = require('merge-stream'); |
| 10 | + |
| 11 | +module.exports = (gulp, config, tasks) => { |
| 12 | + function sprite() { |
| 13 | + const spriteData = gulp.src(config.sprite.src) |
| 14 | + .pipe(spritesmith({ |
| 15 | + imgName: config.sprite.imgName, |
| 16 | + imgPath: `${config.sprite.imgPathPrefix}${config.sprite.imgName}`, |
| 17 | + cssName: config.sprite.cssName, |
| 18 | + cssSpritesheetName: config.sprite.spritesheetName, |
| 19 | + retinaSrcFilter: config.sprite.retina.enabled ? config.sprite.retina.filter : undefined, |
| 20 | + retinaImgName: config.sprite.retina.enabled ? config.sprite.retina.imgName : undefined, |
| 21 | + retinaImgPath: config.sprite.retina.enabled ? `${config.sprite.imgPathPrefix}${config.sprite.retina.imgName}` : undefined, |
| 22 | + cssRetinaSpritesheetName: config.sprite.retina.enabled ? `${config.sprite.spritesheetName}-2x` : undefined, |
| 23 | + cssVarMap(datas) { |
| 24 | + // eslint-disable-next-line no-param-reassign |
| 25 | + datas.name = `${config.sprite.spritesheetName}-${datas.name}`; |
| 26 | + } |
| 27 | + })); |
| 28 | + |
| 29 | + // Pipe image stream through image optimizer and onto disk |
| 30 | + const imgStream = spriteData.img |
| 31 | + // DEV: We must buffer our stream into a Buffer for `imagemin` |
| 32 | + .pipe(buffer()) |
| 33 | + .pipe(gulpif(config.sprite.imagemin, imagemin())) |
| 34 | + .pipe(gulp.dest(config.sprite.imgDest)); |
| 35 | + |
| 36 | + // Pipe CSS stream onto disk |
| 37 | + const cssStream = spriteData.css |
| 38 | + .pipe(gulp.dest(config.sprite.cssDest)); |
| 39 | + |
| 40 | + // Return a merged stream to handle both `end` events |
| 41 | + return merge(imgStream, cssStream); |
| 42 | + } |
| 43 | + |
| 44 | + sprite.description = 'Generates a sprite (img and scss files).'; |
| 45 | + |
| 46 | + gulp.task('sprite', sprite); |
| 47 | + |
| 48 | + gulp.task('clean:sprite', (done) => { |
| 49 | + del([ |
| 50 | + join(config.sprite.imgDest, config.sprite.imgName), |
| 51 | + join(config.sprite.cssDest, config.sprite.cssName) |
| 52 | + ], { force: true }).then(() => { |
| 53 | + done(); |
| 54 | + }); |
| 55 | + }); |
| 56 | + |
| 57 | + gulp.task('watch:sprite', () => { |
| 58 | + gulp.watch(config.sprite.src, sprite); |
| 59 | + }); |
| 60 | + |
| 61 | + tasks.watch.push('watch:sprite'); |
| 62 | + |
| 63 | + tasks.compile.push('sprite'); |
| 64 | + |
| 65 | + tasks.clean.push('clean:sprite'); |
| 66 | +}; |
0 commit comments