My simplified filesystem:
|webpack.config.js
|package.json
|dist
|-index.html
|src
|-index.js
|card
|-card.js
|images
|-imageImporter.js
|-coffee.jpg
|-chocolate.jpg
|-...
I want to write something along the lines of:
imageImporter.js
const images = [];
const imageContext = require.context('./', false, /.(jpg|jpeg|png)$/);
imageContext.keys().forEach((imagePath) => {
images.push(imagePath);
});
export default images;
Puts all the image paths in an array images
index.js
import images from './images/imageImporter.js';
import {dom_createCard} from './card/card.js';
let dom_contentDiv = document.querySelector('div#content');
const dom_createCardsHolder = () => {
let dom_cardsHolder = document.createElement('div');
for (let i=0; i< images.length; i++) {
let imagePath = "../images/"+images[i].substring(2);
let dom_card = dom_createCard(imagePath); // THE CALL IS HERE
dom_cardsHolder.appendChild(dom_card);
}
return dom_cardsHolder;
}
dom_contentDiv.appendChild(dom_createCardsHolder());
Puts all image cards in the dom_cardsHolder
card.js
require.context('../images', false, /.(png|jpg|jpeg|gif|svg)$/);
const dom_createCard = (imagePath) => {
let dom_card = document.createElement('img');
console.log("image path given to me is:"+ imagePath);
// Prints: image path given to me is:../images/coffee.jpg
dom_card.src = imagePath; // WHAT TO DO HERE INSTEAD?
dom_card.width = 300;
return dom_card;
}
export {dom_createCard};
Creates image card
package.json
module: {
rules: [
{
test: /.(png|svg|jpg|jpeg|gif)$/i,
type: 'asset/resource',
},
],
},
Bug
Things don’t work. After printing all the image paths it gives me:
GET http://127.0.0.1:5500/images/<Image Name>.jpg 404 (Not Found)
Note
If in card.js i do instead
import coffeeImage from '../images/coffee.jpg'
// ...
const dom_createCard = (imagePath) => {
// ...
dom_card.src = coffeeImage;
// ...
}
// ...
It works (but it just prints the coffee.jpg and not the other images)


