lifenautjoe/webpack-starter-basic

How to load SVG images?

UlpiusCode opened this issue · 11 comments

Nice starter! How I can load SVG images in html and background: url()?

Thanks a lot!

can you help me?

If you want to use svg files, you have to add a file-loader in your webpack.dev.js and webpack.prod.js config files (in rules[] ) :

...
{
    test: /\.svg$/, 
    loader: 'file-loader' 
}
...

@washaweb this boilerplate use url-loader to loading images, why for svg images i need to use file-loader?
can I add svg here: test: /\.(png|jpg|gif|svg)$/, and load with url-loader? or from file-loader is better?

How can I reference to the SVG file in the index.html after I added the loader to webpack's config files? <img src="<% require('.src/path/to/image.svg') %>"> doesn't seem to work - it outputs only an empty string.

@chrisschaetzlein either remove the '.' at the beginning of the SVG path or add a slash just after. You URL should look like this:

<%= require('./src/path/to/image.svg') %>
or:
<%= require('src/path/to/image.svg') %>

@washaweb That was a typo in my comment, sorry. I already had ./src/path/to/image.svg. Webpack seems to find the file, it's included in the console output. Doesn't output anything to index.html though.

@UlpiusCode You could do that (using url-loader for your svg images), but doing so, SVG code would be converted in a base64 encoded image.
That is not a really a good thing if you intend to later modify your SVG code with CSS or JavaScript interactions.

@chrisschaetzlein do you place this code in a <img src=""> tag ?

@washaweb jeez, I started the include in the .html file with <% require instead of <%= require... sorry! It works with the latter, obviously 🙄

;-)

Thanks for the help @washaweb ! And sorry I couldn't look into this everyone else, stressing out over deadlines currently.

Will incorporate the solution into the README.