Dynamically import images from a directory using webpack

Dynamically import images from a directory using webpack

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.

Leave a Reply

Your email address will not be published. Required fields are marked *