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

React+Webpack中相对路径渲染图片报404的问题求助

React项目中图片相对路径404问题解决

在React应用里渲染图片时,通过import导入图片能正常显示,但直接写相对路径./images/test.jpg会触发浏览器报错“failed to load resource..404 not found”,需要实现相对路径加载图片的功能。


项目代码与结构

App.js

import React from 'react';
import Img from './images/test.jpg';

function App() {
   return(
      <div className="App">
         <img src={Img} alt="test" /> // option-1 正常显示
         <img src='./images/test.jpg' alt="test-2" /> // option-2 404错误
      </div>
    );
}

webpack.config.js

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: './src/index.js',
  output: {
     path: path.join(__dirname,'/dist'),
     filename: 'bundle.js'
  },
  plugins: [
     new HtmlWebpackPlugin({ template: './src/index.html' })
  ],
  module: {
     rules: [
          {
             test: /\.js$/,
             exclude: /node_modules/,
             use: {
                  loader: 'babel-loader',
                  options: {
                     presets: ['@babel/preset-env','@babel/preset-react']
                  }
             }
         },
         {
            test: /\.css$/,
            use: ['style-loader','css-loader']
         },
         {
            test: /\.jpg$/,
            type: 'asset/resource'
         }
    ]
  }
}

项目目录结构

-node_modules
-src
  -components
  -css
  -images
     -test.jpg
  -App.js
  -index.html
  -index.js
-package.json
-webpack.config.js

尝试过的无效操作

曾修改webpack的图片规则为以下配置,结果导致原本正常的import导入方式也失效:

{
    test: /\.js$/,
    use: ['file-loader','url-loader']
}

有效解决方案

方案1:调整webpack配置,对齐资源路径

修改webpack.config.js的两处配置,确保打包后图片的输出路径和代码里的相对路径匹配:

  1. 在output中添加publicPath,指定资源的基础路径:
output: {
  path: path.join(__dirname,'/dist'),
  filename: 'bundle.js',
  publicPath: './' // 新增这一行
},
  1. 修改图片的asset/resource规则,指定图片打包后的输出目录:
{
  test: /\.jpg$/,
  type: 'asset/resource',
  generator: {
    filename: 'images/[name][ext]' // 指定图片输出到dist/images目录
  }
}

这样打包后,图片会被放到dist/images目录下,HTML文件在dist根目录,相对路径./images/test.jpg就能正确指向图片资源。

方案2:利用public目录存放静态资源

在项目根目录创建public文件夹,把images/test.jpg移动到public/images下,然后在代码里使用根相对路径:

<img src='/images/test.jpg' alt="test-2" />

webpack会直接把public目录下的所有文件复制到dist根目录,浏览器可以通过根路径直接访问这些静态资源,无需额外配置。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 20:39:19