React迁移Next.js:如何导入SVG作为ReactComponent?解决模块找不到报错
问题描述
从React项目迁移到Next.js时,根目录assets文件夹存放大量SVG,在constants.js中通过ReactComponent方式导入SVG,出现模块找不到错误:
Module not found: Can't resolve '../../../assets/skills/html5.svg'
1 | import { ReactComponent as HTML } from "../../../assets/skills/html5.svg";
2 | import { ReactComponent as CSS } from "../../../assets/skills/css.svg";
constants.js代码:
import { ReactComponent as HTML } from "../../../assets/skills/html5.svg"; import { ReactComponent as CSS } from "../../../assets/skills/css.svg"; export const SKILLS = [ { name: "html", image: HTML, // SVG Component }, { name: "css", image: CSS, }, ]
文件夹结构:
解决方案
Next.js默认不支持Create React App那样直接导入ReactComponent,可通过以下方式解决:
方法1:配置@svgr/webpack支持ReactComponent导入
在项目根目录创建/修改next.config.js,添加webpack规则让@svgr处理SVG:
/** @type {import('next').NextConfig} */ const nextConfig = { webpack(config) { // 配置svg文件使用@svgr/webpack config.module.rules.push({ test: /\.svg$/i, issuer: /\.[jt]sx?$/, use: ['@svgr/webpack'], }); return config; }, }; module.exports = nextConfig;
安装依赖:
npm install @svgr/webpack --save-dev # 或使用yarn yarn add @svgr/webpack --dev
配置完成后,原constants.js代码可直接使用,无需修改。
方法2:将SVG转为独立React组件
把每个SVG的内容复制出来,创建对应的React组件文件,比如HTMLIcon.js:
export default function HTMLIcon() { return ( <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> {/* 粘贴html5.svg的原始内容 */} </svg> ); }
之后在constants.js中导入这些组件:
import HTMLIcon from '../components/icons/HTMLIcon'; import CSSIcon from '../components/icons/CSSIcon'; export const SKILLS = [ { name: "html", image: HTMLIcon, }, { name: "css", image: CSSIcon, }, ]
该方式无需额外webpack配置,适合SVG数量较少的场景。
方法3:用Next.js Image组件展示SVG(仅图片展示场景)
如果仅需展示SVG图片,无需作为React组件使用,可直接用Next.js的Image组件,在常量中存储SVG路径:
import Image from 'next/image'; export const SKILLS = [ { name: "html", image: '../../../assets/skills/html5.svg', }, { name: "css", image: '../../../assets/skills/css.svg', }, ] // 页面组件中使用示例: {SKILLS.map(skill => ( <Image src={skill.image} alt={skill.name} width={48} height={48} /> ))}
本地SVG资源无需额外配置域名,直接使用即可。
内容的提问来源于stack exchange,提问作者r121
相关产品推荐
相关产品推荐

