Loading static and dynamic images with Webpack

Posted

Webpack and image assets

Loading and handling images with Webpack works pretty well. It allows you to resolve paths, handles cachebust, allows to decode them to Base64, etc.

Usually, to make it work you going to use file-loader or url-loader.

Or since Webpack 5 you define asset/resource type.

Static images

You just specify in webpack.config.js something like this:

{
    test: /\.(jpg|png|svg)$/,
    type: 'asset/resource',
    include: './path/to/images'
}

and require image somewhere in a template:

const pathToCat = require('./path/to/cats/grumpy-cat.png');

const Cat = () => (
    <img
        src='${pathToCat}'
        alt='Grumpy Cat'
    />
);

Dynamic images

But what to do when you have multiple images to display?

const cats = [
    'black-cat.png',
    'white-cat.png',
    'grumpy-cat.png',
    'rainbow-cat.png'
];

const Cats = () => cats.map(name => (
    <img
        src='./path/to/cats/${name}'
        alt='${name}'
    />
));

That’s it!

Updated