/
compressIconfont.js
69 lines (57 loc) · 2.24 KB
/
compressIconfont.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
const fs = require("fs");
const changeCase = require("change-case");
const svgIcon = require("./src/Zcon/svgIcon");
const svgCache = {};
svgIcon.forEach((key) => {
svgCache[key] = true;
});
const text = fs.readFileSync("./assets/iconfont/iconfont.js", "utf-8");
const startSeperator = "<svg><symbol";
const startIndex = text.indexOf(startSeperator) + startSeperator.length;
const endIndex = text.indexOf("</symbol></svg>", startIndex);
const svgtext = text.substr(startIndex, endIndex - startIndex);
const separator = "</symbol><symbol";
const singleIcon = svgtext.split(separator);
const jsLine = {};
const specialViewBox = {};
const toJson = (str) => {
const start = str.indexOf("<path");
const content = str.substr(start);
const contentArr = content.split("</path><path").map((subStr) => {
const res = {};
subStr.match(/\w+="[^"]+"/g).forEach((condition) => {
const [key, value] = condition.split("=");
res[key] = value.replace(/"/g, "");
});
return res;
});
return contentArr;
};
const newIcon = singleIcon.map((t) => {
const start = t.indexOf("id=\"") + 4;
const end = t.indexOf("\"", start);
const id = t.substr(start, end - start)
.replace("zteicon-", "");
const hasColor = /fill="[^"]+"/.test(t);
const viewBox = t.match(/viewBox="[^"]+"/);
if (viewBox.length === 1) {
const viewBoxValue = viewBox[0].split("=")[1].replace(/"/g, "");
if (viewBoxValue !== "0 0 1024 1024") {
specialViewBox[id] = viewBoxValue;
}
}
let res = t;
if (!svgCache[id] && hasColor) {
res = t.replace(/fill="[^"]+"/g, "");
}
jsLine[id] = toJson(res);
return res;
});
fs.writeFileSync("./assets/iconfont/iconfont.js", `${text.substr(0, startIndex)}${newIcon.join(separator)}${text.substr(endIndex)}`);
fs.writeFileSync("./assets/iconfont/iconfont-es.dev.js", `module.exports = ${JSON.stringify({ icon: jsLine, specialViewBox })};`);
/* 模块化 */
const moduleString = Object.keys(jsLine).map((key) => {
const camelKey = changeCase.camelCase(`icon-${key}`).replace(/_/g, "");
return `export const ${camelKey} = ${JSON.stringify(jsLine[key])};\n\n`;
}).join("");
fs.writeFileSync("./assets/iconfont/iconfont-modules.js", `${moduleString} export const specialViewBox = ${JSON.stringify(specialViewBox)}`);