Webpack from A to Asia: Webpack Url Loader

Tram Ho

Webpack from A to Asia with kentrung

In this tutorial we will learn how to set up Webpack to use images in your application via url-loader , it helps us to encode images into base64 URIs string, let’s learn how to load images. how to get images into Javascript .

1. Prepare the file

Code file dist/index.html

In the src folder, we put the image we want to import inside the assets (resources) folder as shown in the below structure

2. Webpack url-loader

url-loader helps us to encode files into base64 string. url-loader works similarly to file-loader but can return DataURL if the file is smaller than the byte limit. To use it we have to install it via npm

After the installation is complete we edit the webpack.config.js file configuration. Image resources ending in png | jpg | gif will be loaded via url-loader.

Code file src/index.js

The meaning of the above code is to create an img tag with src is the image path in the import, alt is the image description. Once created, insert this image into the HTML tag with the id as root.

That’s it, the configuration part, now we run webpack to see how: npm run dev

Now run the file dist/index.html and see the code in F12

We see the path of the image now is a very long base64 string and that is the url-loader . If you want to learn what base64 is, the advantages and disadvantages of using it, you can refer to this link to read more: http://blogchubang.blogspot.com/2016/09/base64-image-o-la -and-can-luu-y-nhung.html

3. Option limit

Limit file size, default is no limit. If the file size is equal to or greater than the limit, wepack uses file-loader (by default) and all query parameters are passed to it. The example below limits the maximum capacity to 8KB


This article is over, hopefully with this article you have added a lot of useful knowledge. See you in the next article!

Share the news now

Source : Viblo