2021-12-27

Loading or including images or asset files in Webpack or ReactJS

In Webpack, or pretty much any frontend framework that relies on it, like ReactJS, if you want to include an image or any asset file, like a PDF, you will need a loader to handle it. You cannot simply write a line of HTML like <img src="pipeline_demo.gif"/>, which will not move the asset file to the compiled output, making asset files inaccessible (404 error).

Instead, you need to use the file-loader module and import an asset file into a variable before using it. Just follow the official instructions and you will a really good result. There are lots of good examples at the end of the official doc. Many answers on Stackoverflow are noises -- like you need to have both file-loader and url-loader.

One thing that you want to pay attention to is that:

ℹ️ By default the filename of the resulting file is the hash of the file's contents with the original extension of the required resource.

So if you do not use any option for file-loader, it will result in a pretty big HTML file with the asset files being super long hash strings, like this: < img src="data:image/gif;base64,R0lG0......" > Hence, you want to use the name option unless you really want the hash strings, e.g., when you only have storage access to HTML files.

Lastly, as someone who is new to MODERN front-end development, I feel front-end development has become so complicated. There are so much stuff to learn at once to start. So many points work together. It's very newbie-unfriendly.

No comments: