How to use Images with Webpack 5 - Setup Tutorial

 by Robin Wieruch
 - Edit this Post

This tutorial is part 2 of 2 in this series.

In this tutorial, you will learn how to set up Webpack to use images as assets for your application. Essentially, there is not much in Webpack to include your desired images for your web application. First, put your image files into one folder of your projects application. For instance, your src/ folder may have a folder assets/ which has a folder images/.

- src/
--- assets/
----- images/
------- myimage.jpg

Second, install a commonly used Webpack loader to include the images into your bundling process:

npm install url-loader --save-dev

And third, include the new loader in your Webpack configuration:

module.exports = {
module: {
rules: [
test: /\.(jpg|png)$/,
use: {
loader: 'url-loader',

It's quite similar to setting up . In this case, we are only bundling the jpg and png image file extensions to our application. However, if you need to include other file extensions for images, make sure to include them here as well. Also the url-loader supports optional options which you should read more about in the official documentation.

Now you are able to import your images as assets from your bundled folders. For instance, in React you can include an image the following way by using an img HTML element and its src attribute:

import React from 'react';
import MyImage from './assets/images/myimage.jpg';
const App = ({ title }) => (
<img src={MyImage} alt="torchlight in the sky" />
export default App;

Hopefully this tutorial has helped you to set up images with Webpack in your JavaScript application. In the comments below, let me know about your techniques to include images.

Keep reading about 

If you happen to have a custom Webpack setup, you may be wondering how to set up CSS with Webpack. This short tutorial walks you through the process. First of all, you need to install a CSS loader and…

Webpack is a JavaScript bundler for your web application. In the past, you had to link JavaScript files manually in HTML files. Nowadays, Webpack takes care about it. In this tutorial, I want to walk…

The Road to React

Learn React by building real world applications. No setup configuration. No tooling. Plain React in 200+ pages of learning material. Learn React like 50.000+ readers.

Get it on Amazon.