Equivalent of require.context from Webpack?
See original GitHub issueChoose one: 🙋 feature request?
🔦 Context
What I’m trying to do is import all images (> 100 images) from a subdirectory, using a regexp. It was possible using webpack require.context (code sample below). I have seen #511 which talks about webpack require.context. This feature was very important (for me atleast) since it saves a tons of lines instead of importing all your assets line by line.
💻 Code Sample
I have a utility function which automatically require all my assets depending of the subdir and regexp I pass as parameters. This is a code sample that work on the latest version of webpack (3.10.0).
// require-all.js
function requireAll(r) {
const dirContent = r.keys().map(r);
const obj = {};
dirContent.map((value) => {
let name = value.substring(value.lastIndexOf('/') + 1, value.indexOf('.'));
obj[name] = value;
});
return obj;
}
export { requireAll };
// foo.js
import { requireAll } from './require-all';
const images = requireAll(require.context('../../assets/', true, /\.png$/));
const audios = requireAll(require.context('../../assets/', true, /\.mp3$/));
Which throw an error because require.context doesn’t exist with Parcel and is specific to webpack:
Uncaught TypeError: require.context is not a function
Any plans on supporting or introduce the equivalent of require.context?
🌍 Your Environment
| Software | Version(s) |
|---|---|
| Parcel | 1.5.1 |
| Node | 8.9.2 |
| npm/Yarn | yarn@1.3.2 |
| Operating System | MacOS High Sierra 10.13.3 |
Issue Analytics
- State:
- Created 6 years ago
- Reactions:6
- Comments:7 (2 by maintainers)

Top Related StackOverflow Question
I’ve made a small util function to retrieve all images from a folder that I was using in my old projects:
This should get you started on how to retrieve files from a folder, including its sub-folder.
More info about
require.contexthere.You should be able to do
const images = require('../../assets/*.png');. But I just tested it and seems like it caused some unrelated bug.So what I can say is that the feature is there, but it has issues. Anyway, can you try that?