如何从ReactJS中的文件夹导入所有图像? [英] How to import all images from a folder in ReactJS?

查看:43
本文介绍了如何从ReactJS中的文件夹导入所有图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从一个文件夹导入所有图像,并希望根据需要使用.但是不能通过以下方法做到这一点.我在做什么?这个:

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) 
    )) 

我在console.log中收到此错误

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'

文件夹结构:

src>
  components>
    Main.jsx
  img>
    [all image files]

推荐答案

在纯JavaScript中这是不可能的,因为导入/导出是静态确定的.

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

如果您使用的是webpack,请查看require.context.您应该能够执行以下操作:

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

这篇关于如何从ReactJS中的文件夹导入所有图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆