@xiping/svg-to-react
v1.0.82
Published
Convert SVG strings to reusable React component code (TSX/JSX).
Readme
@xiping/svg-to-react
将 SVG 字符串转换为可复用的 React 组件代码(TSX / JSX)。
特性
- 支持输出
tsx和jsx两种组件代码 - 自动将 SVG 属性名转换为 React 兼容的
camelCase - 自动将
fill/stroke统一为currentColor(保留none) - 清理内部
id,降低多图标场景下的 DOM id 冲突风险 - 支持在浏览器和 Node.js 环境中解析 SVG
安装
npm i @xiping/svg-to-react快速开始
import { convertToReactComponent } from "@xiping/svg-to-react";
const svg = `<svg viewBox="0 0 24 24" fill="#333"><path d="M12 2l4 8h-8z"/></svg>`;
const code = convertToReactComponent(svg, "TriangleIcon", "tsx");
console.log(code);CLI(仅 Node.js)
命令行用于从本地 .svg 文件生成组件文件;仅在 Node 环境运行。库本身的 import 仍可在浏览器与 Node 中使用。
npx @xiping/svg-to-react <input.svg> [options]| 选项 | 说明 |
|------|------|
| -o, --out-dir <dir> | 输出目录,默认与输入文件同目录 |
| -f, --out-file <name> | 输出文件名(仅 basename)。默认由输入文件主名转 PascalCase,并加 .tsx / .jsx |
| --type <tsx 或 jsx> | 输出格式,默认 tsx |
| --jsx | 等价于 --type jsx |
| -h, --help | 帮助 |
示例:
npx @xiping/svg-to-react ./assets/icon.svg
npx @xiping/svg-to-react ./assets/icon.svg -o ./src/icons -f ArrowIcon.tsx
npx @xiping/svg-to-react ./assets/icon.svg --jsx -f ArrowIcon.jsxAPI
formatSvg(svgString: string): string
规范化 SVG 字符串,主要用于稳定化格式输出(属性排序、空白压缩、自闭合标签展开)。
convertToReactComponent(svgString: string, name: string, fileType: "tsx" | "jsx"): string
将 SVG 字符串转换为 React 组件代码字符串。
svgString: 原始 SVG 文本(根节点必须是<svg>)name: 组件名,例如ArrowLeftIconfileType: 目标输出格式,"tsx"或"jsx"
返回值为完整组件源码字符串,默认包含:
title属性(用于可访问性标题)size属性(默认24)- 其余透传给
<svg>的标准属性(...props)
输出示例(TSX)
import React from "react";
interface TriangleIconProps extends React.SVGProps<SVGSVGElement> {
title?: string;
size?: number;
}
export const TriangleIcon = ({ title, size = 24, ...props }: TriangleIconProps) => (
<svg width={size} height={size} viewBox="0 0 24 24" {...props}>
{title && <title>{title}</title>}
<path d="M12 2l4 8h-8z" fill="currentColor" />
</svg>
);
TriangleIcon.displayName = "TriangleIcon";
export default TriangleIcon;错误处理
当输入不是合法 SVG,或者根节点不是 <svg> 时会抛出错误:
Invalid SVG: root element must be <svg>.本地开发
仓库使用 pnpm 管理依赖。在 monorepo 根目录或本包目录下可执行:
pnpm --filter @xiping/svg-to-react run build
pnpm --filter @xiping/svg-to-react run typecheck在 packages/svg-to-react 目录下也可直接:
pnpm run build
pnpm run dev
pnpm run clean
pnpm run typecheckLicense
MIT
