javascriptsvgoptimizationgulpgulp-imagemin

Gulp imagemin optimization removes svg symbol


This is the first time I use Gulp task-runner or any kind of task-runner. I hope I state my problem in an understandable way.

I have an svg file named svg-system.svg which contains:

<svg xmlns="http://www.w3.org/2000/svg">
    <!-- facebook icon -->
    <symbol id="facebook" role="img" aria-labelledby="title desc" viewBox="0 0 9.3 20">
        <title id="title">Logo af Facebook</title>
        <desc id="desc">Logoet bruges til link indikator for at tilgå vores Facebook side eller dele os.</desc>
        <path d="M9.3,6.5L8.9,10H6.1c0,4.5,0,10,0,10H2c0,0,0-5.5,0-10H0V6.5h2V4.2C2,2.6,2.8,0,6.2,0l3.1,0v3.4
        c0,0-1.9,0-2.2,0c-0.4,0-0.9,0.2-0.9,1v2.1H9.3z"/>
    </symbol>
</svg>

And I would like to compress the file / optimize it for my dist to save some kilobytes.

My confiq in gulpfile.js looks like this:

gulp.task('images', function() {
  return gulp.src('app/images/**/*.+(png|jpg|jpeg|gif|svg)')
    // Caching images that ran through imagemin
    .pipe(cache(imagemin({
        options: {
            optimizationLevel: 3,
            progessive: true,
            interlaced: true,
            removeViewBox:false,
            removeUselessStrokeAndFill:false,
            cleanupIDs:false
        }
    })))
    .pipe(gulp.dest('dist/images'));
});

When I run the task it outputs my svg-system.svg with this content only:

<svg xmlns="http://www.w3.org/2000/svg"/>

Any suggestions or have you seen this issue yourself and fixed it? Cheers.


Solution

  • You have the right general idea: setting cleanupIDs to false will indeed keep the <symbol> around. However the way you're doing it is wrong.

    You're trying to pass an options object to imagemin(). While gulp-imagemin does in fact have an options argument, it only supports the verbose option. None of the options you specify are passed along to svgo.

    You need to explicitly pass those options to the svgo plugin. The way you do this is honestly pretty weird and complicated, but here you go:

    imagemin([
      imagemin.svgo({
        plugins: [
          { optimizationLevel: 3 },
          { progessive: true },
          { interlaced: true },
          { removeViewBox: false },
          { removeUselessStrokeAndFill: false },
          { cleanupIDs: false }
       ]
     }),
     imagemin.gifsicle(),
     imagemin.jpegtran(),
     imagemin.optipng()
    ])