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

create-react-app嵌套路由下Vivus加载SVG失败问题求助

Solution for Vivus SVG Loading Failure in Nested React Routes

The error occurs because your SVG uses a relative file path, which resolves differently depending on the current route:

  • At /market-applications, the path images/svg/... points to /market-applications/images/svg/... (correct)
  • At /market-applications/transportation, it tries to load /market-applications/transportation/images/svg/... (incorrect, this path doesn't exist)

Here are three reliable fixes:

1. Use an Absolute Path with process.env.PUBLIC_URL

Update your SVG path to include process.env.PUBLIC_URL to ensure it always points to the correct location in your public folder:

// Replace this relative path
const svgPath = "images/svg/linea/linea-basic-map.svg";

// With this absolute path
const svgPath = `${process.env.PUBLIC_URL}/images/svg/linea/linea-basic-map.svg`;

This works because process.env.PUBLIC_URL resolves to your app's base URL (e.g., / for localhost, or your deployed subpath), ensuring the SVG is loaded from the root public directory regardless of the current route.

2. Import the SVG Directly as a Module

React allows you to import image files directly, which automatically resolves the correct URL for you:

// Import the SVG in your component file (adjust the relative import path to match your project structure)
import mapSvg from "../images/svg/linea/linea-basic-map.svg";

// Pass the imported variable to Vivus
<VivusComponent svg={mapSvg} ... />

This method is preferred because React handles path resolution internally, avoiding route-related path issues entirely.

3. Fix Route Configuration (If Applicable)

Check your nested route paths—you may be incorrectly prepending process.env.PUBLIC_URL to child routes. In React Router v6, child routes are relative to their parent route by default. Update your route config to:

<Route path={`${process.env.PUBLIC_URL}/market-applications`}>
  <Route index element={<MarketApplication/>} />
  {/* Remove process.env.PUBLIC_URL from child paths */}
  <Route path="transportation" element={<Transportation/>} />
  <Route path="grid" element={<Grid />} />
  <Route path="work" element={<Work/>} />
</Route>

If process.env.PUBLIC_URL is non-empty (e.g., for a subpath deployment), this ensures the full route path resolves correctly (e.g., /my-app/market-applications/transportation).


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 03:07:13