使用 webpack 从目录中动态导入图像 [英] Dynamically import images from a directory using webpack

查看:28
本文介绍了使用 webpack 从目录中动态导入图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我目前通过 ES6 在 webpack 中导入图像和图标的工作流程:

So here's my current workflow for importing images and icons in webpack via ES6:

import cat from './images/cat1.jpg'
import cat2 from './images/cat2.svg'
import doggy from './images/doggy.png'
import turtle from './images/turtle.png'

<img src={doggy} />

这很快就会变得一团糟.这是我想要的:

This gets messy quick. Here's what I want:

import * from './images'

<img src={doggy} />
<img src={turtle} />

我觉得必须有某种方法可以将特定目录中的所有文件动态导入为其名称无扩展名,然后根据需要使用这些文件.

I feel like there must be some way to dynamically import all files from a specific directory as their name sans extension, and then use those files as needed.

有人看过这个,或者对最好的方法有什么想法吗?

Anyone seen this done, or have any thoughts on the best way to go about it?

更新:

使用选定的答案,我能够做到这一点:

Using the selected answer, I was able to do this:

function importAll(r) {
  let images = {};
  r.keys().map((item, index) => { images[item.replace('./', '')] = r(item); });
  return images;
}

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

<img src={images['doggy.png']} />

推荐答案

我觉得必须有某种方法可以将特定目录中的所有文件动态导入为其名称无扩展名,然后根据需要使用这些文件.

I feel like there must be some way to dynamically import all files from a specific directory as their name sans extension, and then use those files as needed.

不在 ES6 中.importexport 的全部意义在于可以静态确定依赖关系,即无需执行代码.

Not in ES6. The whole point of import and export is that dependencies can be determined statically, i.e. without executing code.

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

But since 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)$/));

这篇关于使用 webpack 从目录中动态导入图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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