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

React SSR编译时图片src不匹配问题的解决方法

Fixing "Prop src did not match" Warning in React SSR with Image Assets

I ran into exactly the same warning when working with React SSR and image assets, and here's how I resolved it by adjusting the webpack configuration:

The Problem Scenario

When compiling React SSR, you'll encounter this mismatch warning:

Warning: Prop src did not match. Server: "6eccc1deda4ab0e5bd5f0ffc12b182d9.png" Client: "/app/b2c50f601d2ca40b58c37c526b62b120.png"

Your image import code is correct:

import logo from './image/logo.png';

And your initial webpack rule for image assets looked like this:

{
  test: /\.(jpe?g|png|gif)$/i,
  use: [
    'file-loader',
    {
      loader: 'image-webpack-loader',
      options: {
        mozjpeg: { enabled: false, progressive: true, quality: 65 },
        optipng: { enabled: false },
        pngquant: { quality: '65-90', speed: 4 },
        gifsicle: { interlaced: false },
        webp: { enabled: false, quality: 75 }
      }
    }
  ]
}

The root issue is that the server-side and client-side webpack builds were generating inconsistent file names and paths for your images. Here's the modified configuration that fixes the warning:

The Working Webpack Rule

{
  test: /\.(png|jpe?g|gif)(\?.*)?$/,
  use: [
    {
      loader: 'file-loader',
      options: {
        name: '[name].[ext]',
        publicPath: 'app/'
      }
    },
    {
      loader: 'image-webpack-loader',
      options: {
        mozjpeg: { progressive: false, quality: 10 },
        optipng: { enabled: false },
        pngquant: { quality: '65-90', speed: 4 },
        gifsicle: { interlaced: false },
        webp: { quality: 75 }
      }
    }
  ]
}

Key Changes & Explanations

  • file-loader adjustments (critical for fixing the mismatch):
    • name: '[name].[ext]': Instead of generating random hashed file names for each build, we retain the original image file name. This ensures both server and client builds output the exact same file name for the same asset.
    • publicPath: 'app/': Sets a uniform base path for all image assets. This aligns the URL structure generated on the server with what the client expects, eliminating the path prefix mismatch.
  • image-webpack-loader tweaks (optional, based on optimization needs):
    • Removed mozjpeg.enabled: false and adjusted progressive/quality settings (this doesn't affect the src mismatch, just image optimization behavior)
    • Removed webp.enabled: false (you can add enabled: true here if you want to turn on WebP support later)

After applying these changes, your server and client builds will generate identical src attributes for image assets, and the Prop mismatch warning will vanish.

内容的提问来源于stack exchange,提问作者Fernando Jose Torres Bermudez

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:53:44