0

Is there any workaround or loader available for having to manually import images?

<img src="../assets/img/user/user-13.jpg" alt="" /> this sort of tags in JSX/JS files

Given that we are dealing with jsx HTML loader doesn't cut it out.

I see these sort of solutions: <img src={process.env.PUBLIC_URL + "/images/test.jpg"}

But in my case, I have to make such changes in 100s of files, so it would be really helpful if there are any loaders that automate such a thing.

1 Answers1

0
export default function App() {

  function importAll(r) {
    let images = {};
    r.keys().map((item, index) => { images[item.replace('./', '')] = r(item); });
    return images;
  }
  
  const images = importAll(require.context('../public/assets', false, /\.(png|jpe?g|svg)$/));
  useEffect(() => {
 
  }, []);
  return (
    <div>
      <p>All My images</p>
     {Object.values(images).map((img,i)=><img key={i} src={img} alt={"an alt"} />) }
    </div>
  );
}
Ryan Zeelie
  • 1,320
  • 5
  • 12
  • Based off stackoverflow.com/q/42118296/15474532 – Ryan Zeelie Jul 14 '22 at 06:33
  • This doesn't work. The above code basically pulls out all the images available in the context and creates a collage. I do not want to automate imports, I want to automate having to manually write ```process.env.PUBLIC_URL ``` in – Ganesh Khadka Jul 14 '22 at 10:58