-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild-icon-sprite.js
More file actions
48 lines (37 loc) · 1.52 KB
/
build-icon-sprite.js
File metadata and controls
48 lines (37 loc) · 1.52 KB
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
const fs = require('node:fs');
const path = require('node:path');
const iconsDir = path.resolve(__dirname, '../assets/icons');
const spritePath = path.resolve(__dirname, '../assets/icons/icon-sprite.svg');
const files = fs
.readdirSync(iconsDir)
.filter((file) => file.endsWith('.svg') && file !== 'icon-sprite.svg')
.sort();
function extractSvgParts(svg) {
const viewBoxMatch = svg.match(/viewBox\s*=\s*"([^"]+)"/i);
const viewBox = viewBoxMatch ? viewBoxMatch[1] : '0 0 24 24';
const bodyMatch = svg.match(/<svg[^>]*>([\s\S]*?)<\/svg>/i);
const body = bodyMatch ? bodyMatch[1].trim() : '';
return { viewBox, body };
}
const symbols = files.map((file) => {
const filePath = path.join(iconsDir, file);
const raw = fs.readFileSync(filePath, 'utf8');
const { viewBox, body } = extractSvgParts(raw);
const id = `ofh-icon-${path.basename(file, '.svg')}`;
return ` <symbol id="${id}" viewBox="${viewBox}">\n${body.split('\n').map((line) => ` ${line}`).join('\n')}\n </symbol>`;
});
const sprite = [
'<svg xmlns="http://www.w3.org/2000/svg" style="display:none" aria-hidden="true">',
...symbols,
'</svg>',
''
].join('\n');
if (fs.existsSync(spritePath)) {
const existingSprite = fs.readFileSync(spritePath, 'utf8');
if (existingSprite === sprite) {
console.log(`Icon sprite unchanged -> ${path.relative(process.cwd(), spritePath)}`);
process.exit(0);
}
}
fs.writeFileSync(spritePath, sprite);
console.log(`Built sprite with ${symbols.length} symbols -> ${path.relative(process.cwd(), spritePath)}`);