'Importing all files from folder and putting them into an array with webpack require.context
So I looked at the docs for webpack, and I'm pretty sure that require.context is what I need to put all my images from a folder in an array.
In the folder "Perruet" I've got three jpg images.
By doing exactly what the doc say:
const cache = {};
function importAll(r) {
r.keys().forEach((key) => (cache[key] = r(key)));
}
importAll(require.context('./img/Perruet', false, /\.jpg$/));
console.log("photo", cache)
The console.log give me this result:

What I need is the "default" value of the image that would give me the path to my image, but I can't get this value. Can someone help me to retrieve this value?
Solution 1:[1]
const cache1 = {
};
function importProjets(r) {
r.keys().forEach((key) => (cache1[key] = r(key)));
}
importProjets(require.context('./img/projets',true,/\.jpg$/));
console.log(cache1)
let vals1 = Object.values(cache1);
console.log(vals1);
let projectArray = [];
let projetsImg = [];
let empty=[];
export {projectArray};
function createArrayProjet(){
for (let i = 0; i < 20; i++){
projetsImg.push(vals1[i].default)
}
projectArray.push(projetsImg);
console.log("projectArrayMiddle",projectArray);
projetsImg=empty;
for (let i = 20; i < vals1.length; i++){
projetsImg.push(vals1[i].default)
}
projectArray.push(projetsImg);
}
createArrayProjet();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | JonyEnglish |
