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']} />
UPDATE It seems like I didnt quite understand the question. @Felix got it right so check his answer. The following code will work in a Nodejs environment only.
Add an
index.js
file in theimages
folderThis will allow you to import everything from another file and Wepback will parse it and load the required files.
It's easy. You can use
require
(a static method, import is just for dynamic files) inside therender
. Like the example below:I have directory of png country flags named like au.png, nl.png etc. So I have:
index.js
I read a file like this:
CountryFlagByCode.js
A functional approach to solve this problem:
Not in ES6. The whole point of
import
andexport
is that dependencies can be determined statically, i.e. without executing code.But since you are using webpack, have a look at
require.context
. You should be able to do the following: