Dynamically import images from a directory using webpack

klinore picture klinore · Feb 8, 2017 · Viewed 68.9k times · Source

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']} />

Answer

Felix Kling picture Felix Kling · Feb 8, 2017

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.

Not in ES6. The whole point of import and export 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:

function importAll(r) {
  return r.keys().map(r);
}

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