javascript 如何从 ReactJS 的文件夹中导入所有图像?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/53762640/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to import all images from a folder in ReactJS?
提问by Chetan Kumar
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
我在 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]
回答by Mosè Raguzzini
This is not possible in plain javascript because import/export are determined statically.
这在普通 javascript 中是不可能的,因为导入/导出是静态确定的。
If you are using webpack, have a look at require.context . You should be able to do the following:
如果您正在使用 webpack,请查看 require.context 。您应该能够执行以下操作:
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
参考:https: //webpack.js.org/guides/dependency-management/#require-context

