Adding SVG support to the asset pipeline

I almost have exactly the same workflow for SVG’s, except I don’t use svg-injector and I have a separate SVG directory in my assets and dist folder.

A little addition is that I automatically generate fallback png’s of the minified SVG’s for older browser support with a SVG sequence task:

// ### SVG
gulp.task('svg', function(callback) {
  runSequence('svgmin', ['svg2png1x', 'svg2png2x'], callback);
});
// `gulp svgmin` - Minify SVG files
gulp.task('svgmin', function() {
  return gulp.src(path.source + 'svg/*.svg')
    .pipe(svgmin())
    .pipe(gulp.dest(path.dist + 'svg'));
});
// `gulp svg2png` - create fallback png's from SVG assets
gulp.task('svg2png1x', function() {
  return gulp.src(path.dist + 'svg/*.svg')
    .pipe(svg2png(1.0))
    .pipe(gulp.dest(path.dist + 'images'));
});
gulp.task('svg2png2x', function() {
  return gulp.src(path.dist + 'svg/*.svg')
    .pipe(svg2png(2.0))
    .pipe(rename({suffix: '@2x'}))
    .pipe(gulp.dest(path.dist + 'images'));
});

I embed my SVG in a object tag with img fallback like this:

<object type="image/svg+xml" data="<?php echo get_stylesheet_directory_uri(); ?>/dist/svg/logo.svg" class="logo">
  <img src="<?php echo get_stylesheet_directory_uri(); ?>/dist/images/logo.png" srcset="<?php echo get_stylesheet_directory_uri(); ?>/dist/images/logo.png 1x, <?php echo get_stylesheet_directory_uri(); ?>/dist/images/logo@2x.png 2x" alt="Logo">
</object>

I guess this could be done more dynamically, but for now it works perfect!

3 Likes