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

使用@svgr/core转换SVG为React组件遇SVGOParseError求助

问题:SVG转React组件时出现SVGOParseError错误

开发项目时需将本地SVG转换为React组件,使用@svgr/core的transform.sync方法进行转换验证,触发SVGOParseError,错误提示为Non-whitespace before first tag,检查SVG内容无前置非空白字符但问题仍存在。

错误原因

你的svgContent变量中存储的是HTML转义后的字符串(比如&lt;对应<,&quot;对应"),SVGO解析器会把这些转义字符视为非空白的前置内容,导致解析失败。

解决方案

将转义后的SVG字符串解码为原始SVG代码后,再传入transform.sync方法。可以使用he库完成HTML转义解码,步骤如下:

  1. 安装he库:
npm install he --save-dev
  1. 修改代码,添加转义解码逻辑:
const fs = require('fs');
const path = require('path');
const he = require('he');
const { transform } = require('@svgr/core');

const outputFilePath = path.resolve(__dirname, 'output.js');

const escapedSvgContent = `&lt;svg width=&quot;100&quot; height=&quot;100&quot; xmlns=&quot;http://www.w3.org/2000/svg&quot;&gt;
    &lt;circle cx=&quot;50&quot; cy=&quot;50&quot; r=&quot;40&quot; stroke=&quot;black&quot; stroke-width=&quot;3&quot; fill=&quot;red&quot; /&gt;
  &lt;/svg&gt;
`;

// 解码为原始SVG代码
const svgContent = he.decode(escapedSvgContent);

try {
  const result = transform.sync(svgContent, {
    plugins: [
      '@svgr/plugin-jsx',
      '@svgr/plugin-svgo',
      '@svgr/plugin-prettier'
    ],
    babel: {
      presets: ['@babel/preset-react'],
    },
  });

  fs.writeFileSync(outputFilePath, result, 'utf8');
  console.log('转换成功!');
} catch (err) {
  console.error('转换错误:', err);
}

额外说明

如果你的SVG是直接从本地文件读取,无需使用转义字符串,直接读取原始内容即可:

// 直接读取本地SVG文件示例
const svgContent = fs.readFileSync(path.resolve(__dirname, 'your-svg-file.svg'), 'utf8');

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 18:42:23