AMHNewsHub

Dynamically import images from a directory using webpack

December 15, 2022 By sanxbot00

To dynamically import images from a directory using webpack, you can use the context module.

First, create a context with the path to your directory of images:

const context = require.context('./images', true, /\.(png|jpg|jpeg|gif|ico|svg)$/);

Next, you can use this context in your code to import the images dynamically:

import React from 'react';

const MyComponent = () => {
  const images = context.keys().map(key => context(key));

  return (
    <div>
      {images.map((image, i) => (
        <img key={i} src={image} alt="" />
      ))}
    </div>
  );
};

export default MyComponent;

The above code will import all the images in the specified directory and render them in a container.