File-loader for large size images

Bharat Tiwari
A beginner’s guide to Webpack 2
2 min readMay 24, 2017

In the previous lesson, we saw how to use url-loader in webpack to bundle images, smaller than the specified limit for the image file size, as base64 strings inlined in our code.

Lets see what happens when we have an image with a size larger than the limit we specified for the url-loader.

  1. Download and add a large-size image ( I downloaded nature.jpg from here ) to the ./src/images folder.

2. In the index.html, add another <img> tag as below:

./src/index.html

3.In the ./src/scripts/app.js, import nature.jpg and set above added <img> tag’s src to the imported file:

Above, we imported our newly added image nature.jpg in app.js (linr # 7). And then on line # 12–13, we have set the src of <img id='frontImg'> to this imported image.

4. Save the file, the dev-server will start compiling our package again.

When webpack encounters the line — import natureImg from '../images/nature.jpg' , it passes on the jpg file’s processing to url-loader. url-loader finds that the size of the file is larger than the specified limit of 8kb, so it passes on the file to the file-loader. Along with the file, it also passes on all of the options we have specified for it, to the file-loader.
File-loader will load the file in the package’s output folder, additionally it will hash the file name(useful for cache-brusting). Webpack will use this file name to set the src of the <img id='frontImg'> element.

Thus index.html page will now show our new image in the browser:

In the next lesson, we’ll see how to use ‘CopyWebpackPlugin’ to copy all our image resources to a dist folder.

--

--