lifenautjoe / webpack-starter-basic

A simple webpack starter project for your basic modern web development needs.
https://lifenautjoe.github.io/webpack-starter-basic/
578 stars 131 forks source link

How to load SVG images? #22

Open UlpiusCode opened 5 years ago

UlpiusCode commented 5 years ago

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

Thanks a lot!

UlpiusCode commented 5 years ago

can you help me?

washaweb commented 5 years ago

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' 
}
...
UlpiusCode commented 5 years ago

@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?

chrisschaetzlein commented 5 years ago

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.

washaweb commented 5 years ago

@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') %>
chrisschaetzlein commented 5 years ago

@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.

washaweb commented 5 years ago

@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.

washaweb commented 5 years ago

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

chrisschaetzlein commented 5 years ago

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

washaweb commented 5 years ago

;-)

lifenautjoe commented 5 years ago

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.