You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Webpack动态从目录生成<img>标签遇404错误求助

批量导入图片并动态生成img标签时出现404错误

项目文件结构

|webpack.config.js
|package.json
|dist
   |-index.html
|src
   |-index.js
   |card
      |-card.js
   |images
      |-imageImporter.js
      |-coffee.jpg
      |-chocolate.jpg
      |-...

现有代码

imageImporter.js

const images = [];
const imageContext = require.context('./', false, /\.(jpg|jpeg|png)$/);

imageContext.keys().forEach((imagePath) => {
  images.push(imagePath);
});

export default 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());

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);
    // 打印结果: image path given to me is:../images/coffee.jpg

    dom_card.src = imagePath; // 此处应如何修改?

    dom_card.width = 300; 
    return dom_card;
}


export {dom_createCard};

Webpack配置(package.json中)

module: {
        rules: [
            {
                test: /\.(png|svg|jpg|jpeg|gif)$/i,
                type: 'asset/resource',
            },
        ],
    },

问题

运行后图片无法加载,控制台报错:

GET http://127.0.0.1:5500/images/<Image Name>.jpg 404 (Not Found)

手动导入单张图片(如下)能正常显示,但无法批量处理:

import coffeeImage from '../images/coffee.jpg'
// ...
const dom_createCard = (imagePath) => {
    // ...
    dom_card.src = coffeeImage;
    // ...
}
// ...

解决方案

问题核心:你传递的是源码中的相对文件路径,但Webpack打包后,图片会被重命名并输出到指定目录(比如dist/assets),原路径在打包产物中不存在,导致404。需要在导入阶段直接获取Webpack处理后的图片资源URL。

1. 修改imageImporter.js,获取打包后的图片URL

把原代码中存储路径改成存储Webpack处理后的资源URL:

const images = [];
const imageContext = require.context('./', false, /\.(jpg|jpeg|png)$/);

imageContext.keys().forEach((imagePath) => {
  // 调用imageContext获取打包后的图片资源URL
  images.push(imageContext(imagePath));
});

export default images;

2. 修改index.js,直接传递处理后的URL

无需手动拼接路径,直接将images数组中的URL传给card.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++) {
        // 直接传入Webpack处理后的图片URL
        let dom_card = dom_createCard(images[i]);
        dom_cardsHolder.appendChild(dom_card);
    }

    return dom_cardsHolder;
}

dom_contentDiv.appendChild(dom_createCardsHolder());

3. 修改card.js,直接使用传入的URL

移除无用的require.context,直接将传入的URL赋值给img的src:

const dom_createCard = (imageUrl) => {
    let dom_card = document.createElement('img');
    console.log("image url given to me is:"+ imageUrl);
    // 此时imageUrl是Webpack打包后的资源路径,比如dist/assets/coffee.abc123.jpg

    dom_card.src = imageUrl;

    dom_card.width = 300; 
    return dom_card;
}

export {dom_createCard};

原理说明

Webpack的require.context调用imageContext(imagePath)时,会触发图片资源的打包流程,返回的是打包后图片的绝对资源路径(相对于输出目录),这个路径能正确指向dist中的图片文件,避免404问题。


内容的提问来源于stack exchange,提问作者Xelphin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 05:33:37