Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(Webpack) Using the url-loader or file-loader, do I really have to include a require() in my .js for every static image I want to include?

I'm still learning webpack, and I was having trouble getting images to show up in my production build until I stumbled upon some code which had a require('path/to/image.png') at the top of a .js file. So I tried it, and lo and behold it works.

This seems wonky to me. Do I really have to include one of these for every static image I need to serve? Is there a better way to do this? This is going to be messy if not.

like image 309
Anj Avatar asked Jun 13 '16 17:06

Anj


People also ask

Why do we need to use a loader when using a Webpack?

Webpack enables use of loaders to preprocess files. This allows you to bundle any static resource way beyond JavaScript. You can easily write your own loaders using Node.

What does file-loader do in Webpack?

Webpack file-loader is a loader used mainly for supporting images such as SVG and PNG, and fonts in your webpack project. If your images are not loading in your webpack app then you probably miss the configuration of file-loader.

What is URL-loader in Webpack?

Webpack's url-loader lets you import arbitrary files, like images. If you import a . png file, url-loader will ensure that import resolves to a Base64 string representing the contents of the file.


2 Answers

You can use the CopyWebpackPlugin to move src files to an assets folder when building the webpack project.

Details in this answer: https://stackoverflow.com/a/33374807/492976

like image 93
charliesneath Avatar answered Oct 13 '22 21:10

charliesneath


There are loaders like css-loader and url-loader which resolve urls to base64 inlined data strings instead of serving up the static asset.

You can see this great guide for how to implement with url-loader. If you are having issues you need to make sure you are using the correct relative path.

'./path/to/image.png'

like image 38
Sean Larkin Avatar answered Oct 13 '22 23:10

Sean Larkin