Import multiple images

I want to import all the images in a folder but don’t want to import them individually with a sequence of lines like

import image1 from "./assets/image1.jpg"
import image2 from "./assets/image2.jpg"
etc…

as everytime a new image is added to the folder the code would need to be updated.

I found some code here: https://stackoverflow.com/questions/42118296/dynamically-import-images-from-a-directory-using-webpack

But it’s quite opaque and I don’t fully understand how it’s working, and in any case it seems that it uses deprecated function.

Does anyone know how this can be done?

Here is my current (working) code in image.js:

import React from "react";
import { styled } from "frontity";
// import photo from "./assets/balloons.jpg"


function importImages(r) {
  // console.log(r)
  let images = {};
  r.keys().map((item) => { images[item.replace('./', '')] = r(item); });
  return images;
}
const images = importImages(require.context('./assets', false, /\.(png|jpe?g|svg)$/));

const ImageElement = ({pic = 'mountains'}) => {
  const filename = pic + '.jpg'
  return <Image src={images[filename]} />
}

export default ImageElement;

Is there a better way?

1 Like

I was thinking that you should use await import() but there’s no way to iterate over the possibilities, like what you do there. So I guess using require.context (which is the old version of import()) is fine, even though is an old API.

I think it’s fine :+1: :slightly_smiling_face:

Keep in mind that Webpack will add any image found in that folder to the bundle. So if there a thousand images, all of them will be added.