如何定义 svg-sprite 的 width/height 并将这些值写入文件(使用 Linux 或 Mac CLI)

How can I define width/height of svg-sprite and write these values to the file (with Linux or Mac CLI)

我正在尝试使用 npm 包 svg-sprite 创建 svg-sprite。最终我得到了精灵,它看起来像这样:

// icons-test.svg
...
<svg viewBox="0 0 108 54" ...>
  <svg height="54" width="54" viewBox="-2 -2 54 54" ...>
    <path d="...”>
   </svg>
  <svg height="54" width="54" viewBox="-2 -2 54 54" ...>
    <path d="...”>
  </svg>
</svg>

要定义此 svg-sprite 的大小(例如宽度),我使用来自 util ImageMagick 的命令 identify

identify -format '%w' icons-test.svg

或者写入文件

echo "$spriteWidth = $(identify -format ‘%w’ icons-test.svg)px" >> styles.styl

问题是在文件中我没有得到完整 svg-sprite 的宽度 (108),但只有最后一个子 svg 图像的宽度 (54),即包含在常见的 svg-sprite 中。

请告诉我我的错误在哪里?如何使 identify return 正确宽度。 或者建议我使用其他变体来解决问题。

我怀疑嵌套的 svg 标签混淆了 ImageMagick 的内部 SVG 解码器。尝试将 SVG 转换为 MVG。它应该丢弃嵌套的 SVG 结构。

$ convert icons-test.svg mvg:-

这将打印以下 MVG 指令。

push graphic-context
viewbox 0 0 108 54
affine 1 0 0 1 0 0
push graphic-context
viewbox 0 0 54 54
affine 1 0 0 1 2 2
push graphic-context
path ''
pop graphic-context
pop graphic-context
push graphic-context
viewbox 0 0 54 54
affine 1 0 0 1 2 2
push graphic-context
path ''
pop graphic-context
pop graphic-context
pop graphic-context

将嵌套的 viewbox 隔离到堆栈上的 graphic-context,您应该能够正确地识别

$ convert icons-test.svg mvg:- | identify -format '%w' mvg:-
#=> 108