Next.js导入public文件夹本地SVG图片提示路径无法解析如何解决
问题解决:Next.js导入public目录SVG提示找不到文件
报错根因
Next.js 对静态资源、SVG 文件的处理规则和普通 React 项目不同:
- public 目录下的资源默认不需要通过 import 导入,直接用
/开头的根路径即可访问 - 默认不支持将 SVG 文件直接作为 React 组件导入,需要额外配置 loader
方案1:直接使用public资源路径(无额外依赖,最推荐)
不需要 import 引入SVG文件,直接将public下的路径存到数组的image字段即可:
// 删掉原有 import Icon 的代码 const DUMMY_CHARACTERISTICS = [ { id: "card1", // public下的资源直接写根路径,不需要加/public前缀 image: "/assets/undraw_barbecue_3x93.svg", title: "Insert text here", description: "Insert text here", } ] const CharacteristicsCard = (props) => { return ( <li id={props.id}> {/* Next.js 内置Image组件需要补充alt属性,否则会报错 */} <Image src={props.image} alt={props.title} width={150} height={150} /> <h1>{props.title}</h1> <p>{props.description}</p> </li> ); };
方案2:将SVG作为React组件导入(适合需要控制SVG内部样式的场景)
如果需要修改SVG的填充色、stroke等内部属性,需要配置svg loader:
- 安装依赖
npm install @svgr/webpack --save-dev
- 修改根目录下的
next.config.js配置
/** @type {import('next').NextConfig} */ const nextConfig = { webpack(config) { config.module.rules.push({ test: /\.svg$/i, issuer: /\.[jt]sx?$/, use: ['@svgr/webpack'], }) return config }, } module.exports = nextConfig
- 重启开发服务后,原有import写法即可生效,注意此时导入的是React组件,不能传入Image组件的src,要直接渲染:
import Icon from "../public/assets/undraw_barbecue_3x93.svg"; const DUMMY_CHARACTERISTICS = [ { id: "card1", image: Icon, title: "Insert text here", description: "Insert text here", } ] const CharacteristicsCard = (props) => { return ( <li id={props.id}> {/* 直接渲染SVG组件,属性直接写在组件上即可 */} <props.image width={150} height={150} fill="#f00" /> <h1>{props.title}</h1> <p>{props.description}</p> </li> ); };
内容的提问来源于stack exchange,提问作者Felipe
相关产品推荐
相关产品推荐

