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?