使用 node.js 从 iconfont.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__占位,以便后面作字符串替换。

http://www.ssnd.com.cn 化妆品OEM代加工

2. 切割 .svg 文件

iconfont 生成的 .svg 文件包含了所有图标的路径,用 /<glyph[^n]*/>/g 可以匹配到每一个图标,并借此将它们分离并存储在一个数组里:

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

 

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

使用正则从分离后的各图标里匹配出其对应的 name、unicode 和路径信息:

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__ 替换成匹配到的路径:

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

本文只简述实现原理,不包含完整代码,完整代码已经上传到 一个 GitHub 仓库中,可以按照其 readme 文件使用,此处不再赘述。

posted @ 2021-07-12 20:04  笑人  阅读(120)  评论(0编辑  收藏  举报