I am wondering how to set up an inline svg with webpack?
I am following the react-webpack-cookbook.
I have my webpack.config set up correctly with the file loader.
However the example shows using a background image like this:
.icon {
background-image: url(./logo.svg);
}
which works fine, but I want to have an inline svg image how do I do this to include my logo.svg inline in my react component?
import React, { Component } from 'react'
class Header extends Component {
render() {
return (
<div className='header'>
<img src={'./logo.svg'} />
</div>
);
}
};
export default Header
Actually Michelle's answer pointed me in the right direction, and that works nicely for loading an svg file with webpack and using it as your
<img>
srcHowever to actually get the inline svg, I needed to do the following:
Instead of file-loader use svg-inline-loader as your svg loader:
{ test: /\.svg$/, loader: 'svg-inline-loader' }
Then to load the svg inline in a component:
It looks like there is an inline svg wrapper for react svg-inline-react which would be another option instead of the
<div dangerouslySetInnerHTML={{__html: mySvg}} />
I hope my late answer will still be useful for someone, because I don't like any of abovementioned options.
The react-svg-loader webpack loader allows you to import SVG icons like JSX components:
and minimum config looks like this:
The best part is that it just outputs the svg file contents, without any extra wrappers and
dangerouslySetInnerHTML
in your code.Similar to another answer using React, there is also a handy Vue plugin as well.
vue-svg-loader just throw it in your configuration and start using. The nice thing is it will also run your svg through SVGO to optimize it.
Configuration
Usage
If I'm not mistaken, since you're using the file loader, you can utilize it in much the same way as any other require. Webpack will turn
require("./logo.svg")
into a path to a file, which it will emit when it bundles.Old question, but I didn't see this solution anywhere so I decided to post it, hoping it will help someone.
If you want to be able to style those SVG icons, you might want to load them with the raw loader:
webpack.config.js:
The import in my view:
The template (Mustache uses 3 brackets to insert the SVG data (URL)unencoded):
this way the SVG data will be inserted instead of the brackets and look like this:
I'm using Backbone with Mustache template engine with Webpack 2.5.1