SVGR 命令行工具 @svgr/cli 完全指南:从单文件转换到目录批量生成 React 组件

原创2026-09-22 13:13:331,916 阅读
文章标签:前端开发工具

SVGR 命令行工具 @svgr/cli 完全指南:从单文件转换到目录批量生成 React 组件

SVGR 的核心使命是把 SVG 图标转换为可直接使用的 React 组件,而 @svgr/cli 正是其中最直接的命令行入口:一条命令即可把单个 SVG 或整个目录树批量转换成 JS / TSX 组件,并自动完成 SVGO 优化、Prettier 格式化、index 导出文件生成等一系列工作。读完本文,你将掌握 @svgr/cli 的安装、全部命令行参数、单文件与目录批量的两种工作模式、配置文件加载优先级,以及 index 模板定制等实战方案。

说明:本文以 packages/cli 包在仓库中的当前实现为准,版本号为 8.1.0,要求 Node.js v14 及以上。

安装与最简使用

@svgr/cli 通常作为项目的开发依赖安装:

npm install --save-dev @svgr/cli
# 或者使用 yarn
yarn add --dev @svgr/cli

也可以不安装,直接用 npx 临时调用:

npx @svgr/cli -- icons/clock-icon.svg

-- 之后的部分被视为文件参数(与 CLI 选项区分开)。从 packages/cli/package.json 可以看到,@svgr/cli 声明了 "bin": { "svgr": "./bin/svgr" },因此安装后可直接使用 svgr 命令;其依赖自研的 @svgr/core、@svgr/plugin-jsx、@svgr/plugin-prettier、@svgr/plugin-svgo 四个核心包,以及 commander(参数解析)、glob(文件匹配)、camelcase / dashify / snake-case(文件名大小写转换)等工具库。

执行 svgr --help 会输出完整的用法与选项列表,核心用法为:

Usage: svgr [options] <file|directory>

两种工作模式:单文件与目录批量

@svgr/cli 根据是否指定 --out-dir 自动选择执行路径。在 packages/cli/src/index.ts 中可以看到这一分派逻辑:

const command = opts.outDir ? dirCommand : fileCommand
await command(opts, program, filenames)

即:有 --out-dir 走目录命令 packages/cli/src/dirCommand.ts,否则走单文件命令 packages/cli/src/fileCommand.ts。

单文件转换:三种输入方式

从文件转换——把文件作为唯一参数传入,结果直接输出到标准输出(stdout):

npx @svgr/cli -- icons/clock-icon.svg

从标准输入(stdin)读取——用 < 重定向文件内容:

npx @svgr/cli < icons/clock-icon.svg

把结果重定向到另一个文件——利用 > 运算符:

npx @svgr/cli -- icons/clock-icon.svg > dist/ClockIcon.js

从源码看,stdin 模式在两种情况下触发(fileCommand.ts):显式传入 --stdin,或者没有文件参数且 stdin 不是 TTY(即管道输入)。stdin 模式下组件名会退化为默认的 SvgComponent,快照测试 packages/cli/src/snapshots/index.test.ts.snap 中 should work with stdin 用例的输出即为 const SvgComponent = (props) => ...。若要保留原始文件名语义,可搭配 --stdin-filepath 指定“假装来自”的路径。

单文件模式还有两条限制(见 index.test.ts 的测试断言):

  • 传入目录而不带 --out-dir 会报错:Directory are not supported without '--out-dir' option instead;
  • 传入多个文件而不用 --out-dir 会报错:Please specify only one filename or use '--out-dir' option。

目录批量转换:核心场景

用 --out-dir 指定输出目录后,源目录树中的每个 SVG 都会被转换为同名 React 组件,并保留目录层级:

npx @svgr/cli --out-dir dist -- icons

输出日志示例(来自 cli.mdx):

icons/web/clock-icon.svg -> dist/web/ClockIcon.js
icons/web/wifi-icon.svg -> dist/web/WifiIcon.js
icons/spinner/cog-icon.svg -> dist/spinner/CogIcon.js
icons/spinner/spinner-icon.svg -> dist/spinner/SpinnerIcon.js

其实现要点(dirCommand.ts):

  • 只处理扩展名为 .svg 或 .SVG 的文件(isCompilable 函数);
  • 目录递归遍历,输出路径 = outDir + 相对源根的目录结构;
  • 转换结束后在每个输出目录生成 index.js(除非使用 --no-index);
  • 快照 index.test.ts.snap 中 should transform a whole directory 用例验证了嵌套目录(nesting/a/c/three.svg)与相对输出路径的行为。

完整选项清单

下表整理自 README.md 与 index.ts 中的 commander 定义,全部选项既可在命令行使用,也可写入配置文件:

选项 说明 默认值
-V, --version 输出版本号 -
--config-file <file> 指定 svgr 配置文件路径 -
--no-runtime-config 禁用运行时配置(.svgrrc、.svgo.yml、.prettierrc) 开启
-d, --out-dir <dirname> 输出到目录(触发目录模式) -
--ignore-existing 配合 --out-dir 时跳过已存在文件 关闭
--ext <ext> 自定义输出文件扩展名 js
--filename-case <case> 文件名大小写:pascal / kebab / camel / snake pascal
--icon [size] 把宽高设为 1em(原生为 24dp),可传数值或带单位字符串 关闭
--jsx-runtime <runtime> JSX 运行时:automatic / classic / classic-preact classic
--typescript 输出 TypeScript 组件 关闭
--native 生成 react-native-svg 支持的组件 关闭
--memo 用 React.memo 包裹组件 关闭
--ref 把 ref 转发到 SVG 根元素(React.forwardRef) 关闭
--no-dimensions 移除根 SVG 的 width / height(保留 viewBox) 保留
--expand-props [position] 控制 {...props} 展开位置:start / end / none end
--svg-props <property=value> 向 svg 元素添加额外属性,可逗号分隔多个 -
--replace-attr-values <old=new> 替换属性值,可逗号分隔多个 -
--template <file> 指定自定义组件模板(需导出函数) -
--index-template <file> 指定自定义 index.js 模板 -
--no-index 关闭 index 文件生成 开启
--title-prop 创建与 props 联动的 title 元素 关闭
--desc-prop 创建与 props 联动的 desc 元素 关闭
--prettier-config <fileOrJson> 指定 Prettier 配置(文件或内联 JSON) -
--no-prettier 禁用 Prettier 格式化 开启
--svgo-config <fileOrJson> 指定 SVGO 配置(文件或内联 JSON) -
--no-svgo 禁用 SVGO 优化 开启
--silent 抑制输出 关闭
--stdin 强制从 stdin 读取 自动判断
--stdin-filepath <path> 声明 stdin 内容对应的文件路径 -
-h, --help 输出帮助信息 -

选项参数的类型化解析

源码中对几个特殊选项做了精细的解析(index.ts):

  • --icon:parseIconSize 会把纯数字字符串转成 number(如 --icon 24 输出 width={24}),带单位的字符串则原样保留(如 --icon 2em 输出 width="2em");
  • --svg-props / --replace-attr-values:parseObjectList 按逗号拆分后逐项解析 key=value,例如 --svg-props "hidden={true},id=hello";
  • --template / --index-template:parseTemplate 从当前工作目录加载模块,若模块有 default 导出则取之,且必须导出函数,否则报错退出;
  • --prettier-config / --svgo-config:parseConfig 支持三种形态——以 rc 结尾的文件按 JSON 读取、.js / .json / .cjs 文件直接 require、其他内容按内联 JSON 解析。

目录模式进阶操作

跳过已生成文件:--ignore-existing

如果你手工修改过某些生成文件,可以使用 --ignore-existing 防止它们被覆盖(不推荐修改生成文件,但提供了逃生通道):

npx @svgr/cli --out-dir dist --ignore-existing -- icons

实现上(dirCommand.ts)会先检测目标文件是否存在,存在则跳过写盘并输出灰色日志;测试用例 index.test.ts 验证了该行为——预先放置 // nothing 内容的 File.js 在转换后内容保持不变。

自定义文件名大小写:--filename-case

默认生成的组件文件采用 PascalCase(clock-icon.svg → ClockIcon.js),可通过 --filename-case 切换:

npx @svgr/cli --out-dir dist --filename-case kebab -- icons

四种取值对应的转换逻辑位于 packages/cli/src/util.ts:

  • pascal:camelCase(filename, { pascalCase: true }),如 multiple---dashes → MultipleDashes;
  • camel:camelCase(filename),如 kebab-case → kebabCase;
  • kebab:dashify(filename.replace(/_/g, '-'), { condense: true }),连字符会被折叠合并;
  • snake:snakeCase(filename),如 kebab-case → kebab_case。

快照 index.test.ts.snap 中 should support different filename cases 一组用例给出了四种命名风格下 __fixtures__/cased 目录的输出文件名对照表。传入未知取值会在 util.ts 抛出 Unknown --filename-case 错误。

关闭 index 生成:--no-index

目录模式下默认会在每个输出目录生成 index.js,方便从目录统一导入所有组件。不需要时可以关闭:

npx @svgr/cli --out-dir dist --no-index -- icons

默认的 index 模板(dirCommand.ts)会把每个组件以命名导出的形式汇总:

export { default as ClockIcon } from './ClockIcon'

并且会为数字开头的文件名加上 Svg 前缀(2.file.svg → export { default as Svg2File } from './2File'),该逻辑在 formatExportName(util.ts)中实现,快照 should add Svg prefix to index.js exports staring with number 给出了验证。若开启了 --typescript,index 文件扩展名自动变为 .ts(不生成 .tsx 的 index),这一行为有专门的测试用例 using typescript option, it creates index with '.ts' extension 验证(该修复来自 6.2.1 版本,见 packages/cli/CHANGELOG.md)。

自定义 index 模板:--index-template

高级场景下可以完全接管 index 文件的生成逻辑。模板是一个接收文件信息数组的函数,v8.0.0 起数组元素包含 path(生成的组件路径)与 originalPath(原始 SVG 路径)两个字段(该变更记录在 CHANGELOG.md 的 v8.0.0 破坏性变更说明中)。示例:

// index-template.js
const path = require('path')

function defaultIndexTemplate(filePaths) {
  const exportEntries = filePaths.map(({ path: filePath, originalPath }) => {
    const basename = path.basename(filePath, path.extname(filePath))
    const exportName = /^\d/.test(basename) ? `Svg${basename}` : basename
    return `export { default as ${exportName} } from './${basename}'`
  })
  return exportEntries.join('\n')
}

module.exports = defaultIndexTemplate

使用:

npx @svgr/cli --out-dir dist --index-template index-template.js -- icons

仓库 fixtures/custom-index-template.js 提供了一个更简短的模板(输出 export { File } from './File' 形式),测试用例 should support --index-template in cli 与 should support custom index.js with directory output(通过 fixtures/custom-index.config.js 配置)都验证了这一能力。

转换行为控制选项

以下选项直接改变生成组件的形态,全部有对应的快照测试佐证(index.test.ts.snap)。

--icon:把 width / height 固定为 1em(或指定数值 / 单位),适用于图标库场景:

npx @svgr/cli --icon -- icons/clock-icon.svg
# 指定尺寸
npx @svgr/cli --icon 24 -- icons/clock-icon.svg
npx @svgr/cli --icon 2em -- icons/clock-icon.svg

--no-dimensions:移除根 SVG 的 width 和 height,但保留 viewBox,让组件可以随父容器伸缩(此行为在 4.2.0 版本修复,见 CHANGELOG.md):

npx @svgr/cli --no-dimensions -- icons/clock-icon.svg

--expand-props:控制 {...props} 展开的位置,none 表示完全不展开(3.0.0 起由 --no-expand-props 演进而来):

npx @svgr/cli --expand-props none -- icons/clock-icon.svg
npx @svgr/cli --expand-props start -- icons/clock-icon.svg

--native:生成使用 react-native-svg 的组件(<Svg> / <Path> 等,并在 3.0.0 起自动使用 forwardRef),需要安装 react-native-svg:

npx @svgr/cli --native -- icons/clock-icon.svg

--memo:用 React.memo 包裹组件减少不必要的重渲染。

--ref:通过 React.forwardRef 把 ref 转发到根 svg 元素:

npx @svgr/cli --ref -- icons/clock-icon.svg

--title-prop / --desc-prop:把静态的 <title> / <desc> 变为与 props 联动的动态版本,并自动补充 aria-labelledby / aria-describedby(无障碍支持,见 6.3.0 与 6.4.0 的 a11y 相关变更):

npx @svgr/cli --title-prop -- icons/clock-icon.svg

--svg-props / --replace-attr-values:前者给 svg 元素追加属性,后者做属性值替换(常见于把硬编码颜色替换为 currentColor 以支持继承):

svgr --replace-attr-values "#fff=currentColor" icon.svg
npx @svgr/cli --svg-props "hidden={true},id=hello" -- icons/clock-icon.svg

--typescript:输出 TSX 组件,props 类型为 SVGProps<SVGSVGElement>,配合 --ref / --title-prop / --desc-prop 时还会生成对应的 SVGRProps 接口(SVGProps 在 8.0.0 中改为 import type 导入,见 CHANGELOG.md)。

--jsx-runtime:automatic 时无需手动导入 React;classic-preact 时引入 import { h } from 'preact'。

配置优先级与运行时配置

命令行选项、配置文件、运行时 rc 文件三者按以下优先级合并(packages/core/src/config.ts):

return { ...DEFAULT_CONFIG, ...baseConfig, ...rcConfig }

即:默认值 < 命令行选项 < 运行时配置文件。注意这与“命令行优先”的常见直觉相反——CLI 选项会被 loadConfig 作为 baseConfig 传入,而搜索到的 .svgrrc 等 rc 配置会覆盖它。正因如此,index.ts 在传入前会把未显式指定的键剔除(noUndefinedKeys),避免 CLI 的默认值污染配置文件;测试 should not override config with cli defaults 专门验证了这一点,其使用的 fixtures/overrides.config.js 配置了 expandProps: false、dimensions: false 等。

运行时配置由 cosmiconfig 驱动,会自动搜索 .svgrrc、svgr.config.js 等文件(config.ts)。可以通过 --config-file 显式指定配置文件,或用 --no-runtime-config 完全禁用运行时配置搜索。测试 packages/cli/src/index.test.ts 中通过 --config-file=__fixtures__/overrides.config.js 验证了显式配置文件的加载。

集成 Prettier 与 SVGO

转换管线默认依次执行 SVGO 优化、JSX 转换、Prettier 格式化三个插件,该插件序列定义在 util.ts:

caller: {
  name: '@svgr/cli',
  defaultPlugins: [svgo, jsx, prettier],
}

Prettier:默认开启,会读取项目的 .prettierrc(在 runtimeConfig 开启时通过 resolveConfig 解析,见 dirCommand.ts)。可用 --no-prettier 关闭,或用 --prettier-config 指定内联 JSON 或配置文件:

npx @svgr/cli --prettier-config '{"tabWidth": 5}' -- icons/clock-icon.svg
npx @svgr/cli --prettier-config .prettierrc -- icons/clock-icon.svg

快照 should support --prettier-config as json 展示了 tabWidth: 5 生效后的缩进效果。历史上 6.2.0 曾修复向 prettier 传递 parser 以避免 deprecation warning(见 CHANGELOG.md)。

SVGO:默认开启,可用 --no-svgo 关闭(保留原始 SVG 结构),或用 --svgo-config 指定配置。--svgo-config 支持 .js、.json、.cjs 文件以及内联 JSON(8.1.0 起支持 svgo.config.cjs,见 CHANGELOG.md):

npx @svgr/cli --svgo-config '{"plugins":[{"name":"preset-default","params":{"overrides":{"removeTitle":false}}}]}' -- icons/clock-icon.svg
npx @svgr/cli --svgo-config svgo.config.js -- icons/clock-icon.svg

快照对比非常直观:关闭 SVGO 时(--no-svgo),file.svg 中多层嵌套的 <g> 与 transform 属性全部保留;开启后则被压缩为单个 <path>。仓库 fixtures/withSvgoConfig 提供了 svgo.config.js 与 svgo.config.cjs 两种真实配置示例,测试逐一验证了这两种扩展名的加载。

自定义组件模板

--template 允许替换整个组件的生成模板。v4.0.0 起模板必须返回 Babel AST(这是该版本的重要破坏性变更,见 CHANGELOG.md)。以 fixtures/custom-index.config.js 中的模板为例,它接收 imports、componentName、props、jsx、exports 等变量,并通过 tpl 标签构造代码:

function template(
  { imports, componentName, props, jsx, exports },
  { tpl }
) {
  return tpl`${imports}
export function ${componentName}(${props}) {
  return ${jsx};
}
`
}

module.exports = { template }

错误处理与常见报错

  • 文件不存在:入口会先对每个 glob 展开后的文件做 stat 检查,不存在的文件统一汇总报错并 exit(2)(index.ts);
  • 目录未配 --out-dir:Directory are not supported without '--out-dir' option instead;
  • 多文件未配 --out-dir:Please specify only one filename or use '--out-dir' option;
  • 配置文件非法:parseConfig 解析失败时报 "<name>" is not valid, please specify a valid file or use a inline JSON;
  • 模板非法:--template / --index-template 加载失败或未导出函数时报错并以状态码 2 退出;
  • 处理单个文件出错:目录模式下会打印 Failed to handle file: <filename> 后抛出(该改进来自 6.3.0 的 output file name when error happen to handling a file,见 CHANGELOG.md)。

错误信息通过 exitError(util.ts)以红色输出到 stderr 并 exit(1)。

深入源码:一条命令的完整执行链路

以 svgr --out-dir dist -- icons 为例,完整调用链为:

  1. commander 解析命令行参数(index.ts);
  2. 用 glob.sync 展开输入参数,逐个校验存在性;
  3. noUndefinedKeys 剔除未显式指定的选项,调用 loadConfig 合并默认值与配置文件(config.ts);
  4. 按 outDir 是否存在分发到 dirCommand(dirCommand.ts);
  5. 递归遍历目录树,对每个 .svg / .SVG 文件调用 convertFile → convert → transform.sync,并注入 <a href="https://link.gitcode.com/i/3b2933bab13c95994541485c5a74e754" target="_blank">svgo, jsx, prettier] 默认插件链([util.ts);
  6. 按 --filename-case 重命名输出文件,写盘并打印 src -> dest 日志;
  7. 若开启 index,则调用 indexTemplate 生成 index.js(必要时经 Prettier 格式化)。

整条链路被 index.test.ts 中的 30 余个端到端测试覆盖,测试直接以子进程执行 bin/svgr,产出 638 行快照(index.test.ts.snap),可以作为理解每个选项实际输出效果的最佳参考。

版本演进要点

从 packages/cli/CHANGELOG.md 可以梳理出 @svgr/cli 关键能力的演进脉络,帮助你判断升级影响:

  • v8.1.0:修复默认尺寸、Prettier 与 SVGO 的组合问题;新增对 svgo.config.cjs 的支持;
  • v8.0.0:新增 snake_case 文件名选项;index 模板改为接收包含 path 与 originalPath 的对象数组(破坏性变更);SVGProps 改为 import type 导入;
  • v7.0.0:升级 SVGO v3,要求 Node.js v14+(破坏性变更);
  • v6.5.x:引入 a11y 属性 role="img" 后又回滚;
  • v6.4.0:为 svg 元素添加 role="img" 属性(a11y);
  • v6.3.0:新增 descProp 选项;处理文件出错时输出文件名;
  • v6.2.1:生成的 index 改用 .ts 扩展名(配合 --typescript);
  • v5.5.0:确保导出名合法;防止 SVGO 移除命名空间;改用 fs.promises 提升性能;
  • v5.4.0:所有 CLI 选项均可写入配置文件;修复 index 生成;组件直接用 memo / forwardRef 包裹;
  • v5.3.0:新增 --typescript 选项;
  • v5.1.0:数字开头的导出加 Svg 前缀;支持自定义 index.js 模板;
  • v4.0.0:新架构,template 必须返回 Babel AST;@svgr/core 不再默认内置 svgo 与 prettier(破坏性变更);
  • v3.0.0:--no-expand-props 改为 --expand-props none 并支持 start / end 位置;svgAttributes 改为 svgProps;--config 改名为 --config-file;默认使用 React.forwardRef(要求 React > 16.3);
  • v2.4.0:新增 svgProps 选项;
  • v2.3.0:升级 Babel v7;
  • v2.1.0:支持自定义文件名大小写。

结语

@svgr/cli 把 SVGO 优化、JSX 转换、Prettier 格式化、目录递归与 index 生成整合进一条命令,是 SVGR 生态中最适合脚本化、CI 化批量处理 SVG 图标库的工具。无论是把单个图标转为组件,还是把整套设计稿导出的图标目录一键生成 React / React Native / TypeScript 组件库,都可以结合本文的选项清单与源码行为说明,直接落地到自己的项目中。

登录后查看全文
svgr