Dwight Watson's blog

Import whole directory in Webpack(er)

This blog post was originally published a little while ago. Please consider that it may no longer be relevant or even accurate.

Like an amateur I've been importing all my assets one-by-one when using Webpacker to get them all listed in the app manifest. It's annoying when adding or removing an image to then update the reference in images/index.js.

import "./arrow-right.svg";
import "./badge-maintenance.svg";
// And so on.

Turns out, there's a better way and you can reduce it all down to one single line of code. Use require.context and pass a regular expression to identify which files you want to import. Boom.

require.context("./", true, /\.(svg|png)$/gim);

A blog about Laravel & Rails by Dwight Watson;

Picture of Dwight Watson

Follow me on Twitter, or GitHub.