How to use Images with Webpack

    Follow on Twitter  

This tutorial is part 2 of 2 in 'Webpack with Images'-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 fonts with Webpack. 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.

Build a Hacker News App along the way. No setup configuration. No tooling. No Redux. Plain React in 200+ pages of learning material. Learn React like 50.000+ readers.

Get the Book for free
comments powered by Disqus

Never miss an article about web development, JavaScript and self-growth.

Take Part

Join 30.000+ Developers

Learn Web Development with JavaScript

Tips and Tricks

Access Tutorials, eBooks and Courses

Personal Development as a Software Engineer