Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
187 views
in Technique[技术] by (71.8m points)

javascript - Importing multiple files in react

I am using create-react-app for my react project. It has got webpack configured for importing images. I wish to import multiple images (say 10) from a images folder into a component. The easiest way of doing this would be to add multiple import statement such as -

import Img0 from '../images/0.png';
import Img1 from '../images/1.png';
import Img2 from '../images/2.png';
import Img3 from '../images/3.png';
import Img4 from '../images/4.png';
import Img5 from '../images/5.png';
import Img6 from '../images/6.png';
...

The above code would not be a good choice when we have multiple files to import. Is there a way to add the import statements in a loop? I tried adding for loop but I was unable to modify the variables Img0, Img1 etc. (using ES6 `` didn't work as it converted the variable to a string)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think maybe a better idea is to use an index file for your images folder.

Supposing you have this structure:

Initial folder structure, where all images are on subfolders inside assets/images

And you need to import all of your images to your HomePage component. You can easily create an index.js file on your images folder, exporting all the images using require, like this:

export const Background = require('./bg/background.jpg');
export const First = require('./photos/first.jpg');
export const Second = require('./photos/second.jpg');
export const LinkedIn = require('./social/linkedin.png');

Then on your component you can import all of them with a single import.

import {
  Background,
  First,
  Second,
  LinkedIn
} from '../../assets/images'

And this would be your final folder structure: Final folder structure where we have an index.js inside assets/images

Hope it helps! ;)

Updated on 25/04/2021:

If you want to use ES6 named imports:

images/index.js:

import Background from './bg/background.jpg';
import First from './photos/first.jpg';
import Second from './photos/second.jpg';
import LinkedIn from './social/linkedin.png';

export {
  Background,
  First,
  Second,
  LinkedIn
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...