问题描述
我目前正在努力从子画面中删除未使用的SVG。为了完成此任务,我使用了purged-svg。 软件包purge-svg使用xml-js将文件转换为SVG。如以下几行所示。
https://github.com/Media24si/purge-svg/blob/master/src/index.js#L188 https://github.com/Media24si/purge-svg/blob/master/src/index.js#L142
从上图的左图是SVG的原始图片,而图的右图是由purge-svg
编译的SVG,因为您可以看到元素正在重新排序,从而带来了rect
和circle
到SVG底部(该图标会中断)。
基于xml-js
的文档:
注意:尽管非紧凑型输出更准确地表示 原始XML比压缩版本要高,非压缩版本要冗长 并占用更多空间。该库提供了两个选项。采用 {compact:false}如果不确定,因为它可以保留所有内容; 否则,如果您想节省空间而不使用{compact:true} 关心混合同名元素并失去顺序。
根据文档,compact: true
似乎没有保留原始顺序。但是,当我更改为false时,SVG的编译就会中断。
fs.writeFileSync(filename,js2xml(svg,{ compact: false,spaces: 2 }))
添加compact: false
将返回一个空的icons.purged.aa00hggjh.svg
文件。如果将其更改为compact: true
,则可以获取SVG,但会重新排序,这会破坏图标。
<symbol id="icon-card-cash-expenses-v2" viewBox="0 0 48 48">
<path d="M24 48c13.255 0 24-10.745 24-24S37.255 0 24 0 0 10.745 0 24s10.745 24 24 24z"/>
<path d="M24 44c11.046 0 20-8.954 20-20S35.046 4 24 4 4 12.954 4 24s8.954 20 20 20z" fill="currentColor"/>
<path d="M23.5 32a7.5 7.5 0 100-15 7.5 7.5 0 000 15z" fill="currentColor"/>
<path d="M21 27.135s1.364.865 3.273.865c1.09 0 2.727-.432 2.727-1.73 0-1.08-.936-1.56-3-2.378l-1.09-.433c-1.092-.432-1.364-1.08-1.364-1.73 0-.78.818-1.729 2.727-1.729 1.309 0 2.363.577 2.727.865" stroke="#fff" stroke-width="1.5" fill="transparent"/>
<path d="M24 20v-2M24 30v-2" stroke="#fff" stroke-width="1.5"/>
<rect x="10" y="15" width="28" height="18" rx="1" fill="#fff"/>
<circle cx="24" cy="24" r="8" fill="currentColor"/>
</symbol>
上面的SVG rect
和circle
应该位于最后2个path
元素上方,以便显示带有美元符号的图标。但是,上面的SVG显示如下:
但是假设显示为:
但是,当我尝试将设置更改为compact: false
时,什么也没返回。
purge () {
const contentIds = PurgeSvg.extractContentIds(this.options.content)
const outSvgs = {}
PurgeSvg.prepareSvgPaths(this.options.svgs).forEach(svgobj => {
const ids = new Set([
...(contentIds[svgobj.filename] || []),...(this.options.whitelist[svgobj.filename] || []),...(this.options.whitelist['*'] || []),])
const svg = xml2js(fs.readFileSync(svgobj.in,'utf8'),{ compact: true })
let symbols = svg.svg.symbol
if (typeof symbols === 'undefined') {
symbols = svg.svg.defs.symbol
}
if (typeof symbols === 'undefined') {
return
}
if (!Array.isArray(symbols)) {
symbols = [symbols]
}
if (!Array.isArray(outSvgs[svgobj.out])) {
outSvgs[svgobj.out] = []
}
outSvgs[svgobj.out].push(
...symbols.filter((s) => ids.has(s._attributes.id)),)
})
for (let filename in outSvgs) {
const svg = {
_declaration: {
_attributes: {
version: '1.0',encoding: 'UTF-8',},svg: {
_attributes: {
xmlns: 'http://www.w3.org/2000/svg',style: 'display: none;',symbol: outSvgs[filename],}
if (!fs.existsSync(path.dirname(filename))) {
fs.mkdirsync(path.dirname(filename))
}
fs.writeFileSync(filename,spaces: 2 }))
}
}
}
有什么方法可以防止在xml-js
中对SVG进行重新排序?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)