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

如何在React中无需显式导入即可加载图片?

React 实现 img 标签 src 自动导入方案

你需要的类似 Angular 的 src 自动导入效果,可通过调整 webpack loader 配置实现,具体操作如下:

  • 首先安装必要依赖,webpack4 及以下版本需要安装 html-loader、file-loader;webpack5 版本仅需安装 html-loader,无需额外安装 file-loader,可直接用内置 asset 模块处理静态资源。
  • 调整 webpack 配置:
    webpack4 及以下版本配置示例:
    module.exports = {
      module: {
        rules: [
          // 处理图片文件
          {
            test: /\.(png|jpe?g|gif|svg)$/i,
            use: [
              {
                loader: 'file-loader',
                options: {
                  // 配置输出后的图片文件名、路径
                  name: '[name].[contenthash].[ext]',
                  outputPath: 'static/images',
                  publicPath: 'static/images'
                }
              }
            ]
          },
          // 处理jsx文件中的img标签属性
          {
            test: /\.jsx?$/,
            exclude: /node_modules/,
            use: [
              'babel-loader',
              {
                loader: 'html-loader',
                options: {
                  // 指定要处理的标签属性
                  attrs: ['img:src', 'img:data-src']
                }
              }
            ]
          }
        ]
      }
    }
    
    webpack5 版本配置示例:
    module.exports = {
      module: {
        rules: [
          // 处理图片文件,用webpack5内置asset模块
          {
            test: /\.(png|jpe?g|gif|svg)$/i,
            type: 'asset/resource',
            generator: {
              filename: 'static/images/[name].[contenthash][ext]'
            }
          },
          // 处理jsx文件中的img标签属性
          {
            test: /\.jsx?$/,
            exclude: /node_modules/,
            use: [
              'babel-loader',
              {
                loader: 'html-loader',
                options: {
                  sources: {
                    list: [
                      {
                        tag: 'img',
                        attribute: 'src',
                        type: 'src'
                      }
                    ]
                  }
                }
              }
            ]
          }
        ]
      }
    }
    
  • 配置完成后即可直接在 jsx/tsx 中填写相对路径的 src,无需手动导入/require,webpack 会自动处理资源导入:
    <img src="../../assets/images/img.png" alt="示例图片" />
    
  • 常见场景适配:
    • 如果是 Create React App 创建的项目,可通过 react-app-rewired + customize-cra 覆盖默认配置,无需执行 eject 操作暴露全部配置。
    • 如果使用 TypeScript,需要在全局类型声明文件中添加图片资源的类型声明,避免类型报错:
      declare module '*.png';
      declare module '*.jpg';
      declare module '*.jpeg';
      declare module '*.gif';
      declare module '*.svg';
      

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 02:06:05