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?
UPDATE:
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']} />
.map
kind of expects a return value. In your case, one would use a good ol'forEach
instead. – Desorbr.keys.().map(...)
directly... – Claresta