我正在为我的React项目使用create-react-app。它已经配置了webpack来导入图像。我希望从一个图像文件夹中导入多个图像(比如10张)到一个组件中。最简单的方法是添加多个import语句,例如-
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';
...
当我们需要导入多个文件时,上面的代码不是一个好选择。是否有一种方法可以在循环中添加导入语句?我尝试添加for循环,但无法修改变量Img0、Img1等(使用ES6的``不起作用,因为它将变量转换为字符串)。
export default function importImages(imagesDirectory) { return importAll( require.context(imagesDirectory, false, /\.(png|jpe?g|svg)$/) ); }
但是会报错TypeError: __webpack_require__(...).context is not a function
。 - Sushmit Sagarrequire.context()
中的所有内容都必须是字面量,因此您不能传递变量,例如imagesDirectory
。 - Qwerp-Derp'/\.png/'
应该是/\.png/
(正则表达式而不是字符串) - Asu