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

React如何从public文件夹导入SVG?能否使用process.env.PUBLIC_URL?

Fixing "Module not found" When Importing SVG from Public Folder

Let's break down what's going on here and how to fix it—this is a super common gotcha with Create React App (CRA) setups, which I'm assuming you're using since you mentioned process.env.PUBLIC_URL.

Why your current import isn't working

CRA treats the public folder as a static asset root, not part of the module system that import uses. When you try to import './public/avatar_1.svg', Webpack (under the hood of CRA) looks for this file relative to your component file within the src directory tree—and it doesn't exist there, hence the error.

Two correct approaches to use your SVG

1. Move the SVG to src and use standard import

If you don't need the SVG to be in public, this is the recommended approach because Webpack can process, optimize, and hash the file for better performance:

  • Move avatar_1.svg to a subfolder in src (e.g., src/assets/avatars/)
  • Import it normally in your component:
    import Avatar1 from '../assets/avatars/avatar_1.svg';
    
    // Then use it in your JSX
    <img src={Avatar1} alt="User avatar" />
    

Bonus: If you want to use the SVG as a React component (so you can style it with CSS-in-JS or modify props), you can leverage CRA's built-in support by importing with ?react: import { ReactComponent as Avatar1 } from '../assets/avatars/avatar_1.svg?react';

2. Keep it in public and use process.env.PUBLIC_URL

If you need the SVG to stay in public (e.g., it's referenced outside React code, or you want it to be a raw static asset), skip the import entirely and build the URL using process.env.PUBLIC_URL:

function MyComponent() {
  const avatarUrl = `${process.env.PUBLIC_URL}/avatar_1.svg`;
  return <img src={avatarUrl} alt="User avatar" />;
}

process.env.PUBLIC_URL is a CRA-specific variable that automatically points to the root of your public folder, whether you're running locally or deploying to a subdirectory (like GitHub Pages). This ensures the path always resolves correctly.

Quick notes to avoid future issues

  • Double-check file names and capitalization—many production servers are case-sensitive, so Avatar_1.svg vs avatar_1.svg will break your asset path.
  • Files in public aren't processed by Webpack, so they won't be minified or hashed. For optimized, cache-friendly assets, stick to the src folder approach.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:47:02