阿里巴巴矢量图标库 (以下称iconfont)提供了不便的图标分享和治理性能。然而因为其图标我的项目独立于代码仓库,往往导致同一我的项目更换开发人员之后,接任者不能持续治理原来的图标库,给开发带来各种不便。

因为 iconfont 生成的 svg 文件含有图标门路以及图标名数据,因而 (对于保留了此 svg 文件的我的项目)能够从此 svg 文件中提取出所有图标,而后上传至图标库,从新构建图标我的项目。

1. svg 文件模板

SVG 的相干常识能够在 SVG | MDN (mozilla.org) 学习。
为了生成残缺的 svg 文件,为其筹备了一个文件模板字符串:

// svg 文件模板const svgTemplate =`<svg    xmlns="http://www.w3.org/2000/svg"    xmlns:xlink="http://www.w3.org/1999/xlink"    t="1584762969678"    class="icon"    viewBox="0 0 1024 1024"    version="1.1"    p-id="12392"    width="200"    height="200">    <defs><style type="text/css"/></defs>    <path d="__PATH__" /></svg>`;

其中的 d 参数为 svg 门路,这里用 __PATH__占位,以便前面作字符串替换。

2. 切割 .svg 文件

iconfont 生成的 .svg 文件蕴含了所有图标的门路,用 /<glyph[^n]*/>/g 能够匹配到每一个图标,并借此将它们拆散并存储在一个数组里:

readFile(resolve(__dirname, svgPath), 'utf8', (err, res) =>{    const iconArray = res.match(/<glyph[^n]*/>/g);}

3. 替换模板文件里的门路

应用正则从拆散后的各图标里匹配出其对应的 nameunicode 和门路信息:

iconArray.forEach(item => {    // 拆散 unicode    const unicode = item.match(/unicode="&#(d+);"/)[1];    // 拆散类名即图标名    const className = item.match(/glyph-name="([w-_]+)"/)[1];    // 拆散门路    const path = item.match(/ d="([^"]*)"/)[1]);});

4. 写入文件

svg 模板字符串中的 __PATH__ 替换成匹配到的 ``

writeFile(    resolve(outputPath, className + '.svg'),    svgTemplate.replace('__PATH__', path),    function(err){if(err){throw err}});

本文只简述实现原理,不蕴含残缺代码,残缺代码曾经上传到 一个 GitHub 仓库中,能够依照其 readme 文件应用,此处不再赘述。