forked from spothq/cryptocurrency-icons
-
Notifications
You must be signed in to change notification settings - Fork 17
/
generate.js
77 lines (68 loc) · 1.61 KB
/
generate.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
69
70
71
72
73
74
75
76
77
const { readdirSync, readFileSync } = require("fs");
const { transform } = require("@svgr/core");
const { join } = require("path");
const esbuild = require("esbuild");
const ICON_DIR = "./svg/icon";
const ICON_COLOR_DIR = "./svg/color";
function findSVGIds(svgString) {
const idRegex = /id="([^"]+)"/g;
const ids = [];
let match;
while ((match = idRegex.exec(svgString)) !== null) {
ids.push(match[1]);
}
return ids;
}
/**
* give all ids in an svg a globally unique value to prevent styling collisions
* @param {string} svgCode
* @param {string} iconName
* @returns
*/
const replaceIds = (svgCode, iconName) => {
const ids = findSVGIds(svgCode);
if (!ids.length) {
return svgCode;
}
let result = svgCode;
ids.forEach((id) => {
result = result
.replaceAll(`id="${id}"`, `id="${iconName}-${id}"`)
.replaceAll(`#${id}`, `#${iconName}-${id}`);
});
return result;
};
const generateComponents = (iconDir) => {
const icons = readdirSync(iconDir);
icons.forEach((file) => {
const [fileName] = file.split(".");
let iconName = fileName;
if (iconName === "index") {
iconName = "indexIcon";
}
const svgPath = join(iconDir, file);
const svgCode = readFileSync(svgPath, "utf8");
const jsCode = transform.sync(
replaceIds(svgCode, iconName),
{
expandProps: "end",
typescript: false,
jsx: false,
},
{ filePath: svgPath }
);
esbuild.buildSync({
outfile: `react/${iconName}.js`,
allowOverwrite: true,
loader: {
".js": "jsx",
},
stdin: {
contents: jsCode,
loader: "jsx",
},
});
});
};
generateComponents(ICON_DIR);
generateComponents(ICON_COLOR_DIR);