小编典典

如何从ReactJS中的文件夹导入所有图像?

reactjs

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

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

我在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]

阅读 716

收藏
2020-07-22

共1个答案

小编典典

在普通的javascript中这是不可能的,因为导入/导出是静态确定的。

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

function importAll(r) {

  return r.keys().map(r);

}



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

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

2020-07-22