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

React中以IMG形式导入SVG失效问题求助

Create React App项目中SVG无法正常显示的问题

我在Create React App项目里无法正常显示SVG,试过多种方法都出现不明错误,怀疑是文件路径问题但路径看起来是正确的,查了大量资料还是没解决,求帮助。

尝试过的方法及结果

方法1:直接使用img标签相对路径

代码:

<img src="../assets/images/logo-cool-earth-white.svg" alt="Cool Earth" />

结果:浏览器只显示alt文本,控制台提示File could not be found。

方法2:import后作为img的src属性值

代码:

import CoolEarth from '../assets/images/logo-cool-earth-white.svg';
// ...
<img src={CoolEarth} alt="Cool Earth" />

方法3:导入为React组件

代码:

import {ReactComponent as CoolEarth} from '../assets/images/logo-cool-earth-white.svg';
// ...
<CoolEarth />

(注:上述img组件和React组件都写在一个返回JSX的函数组件内部)

方法2和3的编译错误信息:

Compiled with problems:

ERROR in ./src/assets/images/logo-cool-earth-white.svg

Module build failed (from ./node_modules/file-loader/dist/cjs.js):
Error: error:0308010C:digital envelope routines::unsupported
    at new Hash (node:internal/crypto/hash:67:19)
    at Object.createHash (node:crypto:133:10)
    at getHashDigest (/Users/username/Documents/Clients/clientname/crypto-transfer/working crypto-transfer/node_modules/loader-utils/lib/getHashDigest.js:46:34)
    at /Users/username/Documents/Clients/clientname/crypto-transfer/working crypto-transfer/node_modules/loader-utils/lib/interpolateName.js:113:11
    at String.replace (<anonymous>)
    at interpolateName (/Users/username/Documents/Clients/clientname/crypto-transfer/working crypto-transfer/node_modules/loader-utils/lib/interpolateName.js:110:8)
    at Object.loader (/Users/username/Documents/Clients/clientname/crypto-transfer/working crypto-transfer/node_modules/file-loader/dist/index.js:29:48)

项目文件结构

src >
 components >
  Video.js
 assets >
  images >
   logo-cool-earth-white.svg
 App.js

(注:包含SVG的Video.js组件在App.js中渲染)

SVG文件内容(简化版)

<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
     viewBox="0 0 95 90" style="enable-background:new 0 0 95 90;" xml:space="preserve">
<path class="st0" d="...">
...
</svg>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 05:15:44