Skip to content

Instantly share code, notes, and snippets.

@jehoshua02
Last active August 29, 2015 14:10
Show Gist options
  • Save jehoshua02/a3ac58dd7e2d8efb30b5 to your computer and use it in GitHub Desktop.
Save jehoshua02/a3ac58dd7e2d8efb30b5 to your computer and use it in GitHub Desktop.
Dreamcode for webpack svg-loader.

The webpack way to load svg?

Every time I use svg images, I want to provide png fallbacks. I was looking into using the file-loader, but I need to do a bit more:

  • Move svg and png fallback files into the destination folder.
  • Bundle a module for the client to check for svg support.
  • Bundle a module for the client that returns the correct url for the image based on svg support.

I hoped there would be an svg-loader but didn't find one in the list. Maybe it's a good idea?

Obviously we only want to check for svg support one time so the svg support test module would be memoized.

I'm using React, so my example would look like this:

my-logo.jsx

var React = require('react');
module.exports = React.createClass({
  render: function () {
    return (
      <img src="{require('my-logo.svg')}" />
    )
  }
});

I would imagine the configs would look something like this:

webpack.config.js

module.exports = {
  module.loaders = [
    { test: /\.svg$/, loader: 'svg-loader' }
  ]
}

Not a requirement in my situation, but a nice to have: the svg-loader could take it one step further and generate the png fallback automatically as well. I'm using gulp-svg2png. The svg-loader can learn something here from gulp-svg2png to generate png. I'm using the scale option to enlarge the png so it is more crisp. Query params could be passed to svg-loader:

webpack.config.js

module.exports = {
  module.loaders = [
    { test: /\.svg$/, loader: 'svg-loader?{png:{scale:2}}' }
  ]
}

What is the "webpack way" to load svgs with png fallbacks? A new loader or some other way?

@jehoshua02
Copy link
Author

Posted Github Issue: webpack/webpack#595

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment