20

I want to import all images from a folder and want to use as needed. But can't do it by following methods. What I am doing? this:

import * as imageSrc from '../img';
let imageUrl = [];
    imageSrc.map(
    imageUrl.push(img) 
    )) 

I am getting this error in console.log

index.js:1452 ./src/components/Main.jsx
Module not found: Can't resolve '../img' in 'G:\Projects\Personal\Portfolios\Portfolio_Main\React_portfolio\portfolio\src\components'

Folder Structure:

src>
  components>
    Main.jsx
  img>
    [all image files]
Chetan Kumar
  • 427
  • 1
  • 3
  • 18

1 Answers1

29

This is not possible in plain javascript because import/export are determined statically.

If you are using webpack, have a look at require.context . You should be able to do the following:

function importAll(r) {
  return r.keys().map(r);
}

const images = importAll(require.context('./', false, /\.(png|jpe?g|svg)$/));

ref: https://webpack.js.org/guides/dependency-management/#require-context

Mosè Raguzzini
  • 15,399
  • 1
  • 31
  • 43