使用@svgr/core转换SVG为React组件遇SVGOParseError求助
问题:SVG转React组件时出现SVGOParseError错误
开发项目时需将本地SVG转换为React组件,使用@svgr/core的transform.sync方法进行转换验证,触发SVGOParseError,错误提示为Non-whitespace before first tag,检查SVG内容无前置非空白字符但问题仍存在。
错误原因
你的svgContent变量中存储的是HTML转义后的字符串(比如<对应<,"对应"),SVGO解析器会把这些转义字符视为非空白的前置内容,导致解析失败。
解决方案
将转义后的SVG字符串解码为原始SVG代码后,再传入transform.sync方法。可以使用he库完成HTML转义解码,步骤如下:
- 安装
he库:
npm install he --save-dev
- 修改代码,添加转义解码逻辑:
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 = `<svg width="100" height="100" xmlns="http://www.w3.org/2000/svg"> <circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" /> </svg> `; // 解码为原始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
相关产品推荐
相关产品推荐

