import { readdirSync, readFileSync, writeFileSync } from 'node:fs'; import { basename, join } from 'node:path'; import { optimize } from 'svgo'; import type { IconSpriteOptions } from './types'; const ROOT_SVG = /^]*)>([\s\S]*)<\/svg>$/; const VIEW_BOX = /viewBox="([^"]+)"/; /** * Optimizes every icon with svgo and joins them into one sprite. Stroke and fill are dropped * from each root, so the `` that references a symbol sets them and a caller can change them. */ export function buildIconSprite({ iconsDir, spriteFile, namesFile, }: IconSpriteOptions): string[] { const files = readdirSync(iconsDir) .filter((file) => file.endsWith('.svg')) .sort(); const names = files.map((file) => basename(file, '.svg')); const symbols = files.map((file, index) => { const { data } = optimize(readFileSync(join(iconsDir, file), 'utf8'), { multipass: true, // svgo 4 keeps the viewBox by default. plugins: ['preset-default'], }); const [, attributes, body] = ROOT_SVG.exec(data) ?? []; const viewBox = VIEW_BOX.exec(attributes ?? '')?.[1]; if (body === undefined || !viewBox) { throw new Error(`${file}: expected one root with a viewBox`); } return `${body}`; }); // Next.js reads a static SVG's size on import, so the root carries one; `` ignores it. writeFileSync( spriteFile, `${symbols.join('')}\n`, ); writeFileSync( namesFile, [ '// Generated by tools/icon-sprite-plugin from src/icons/*.svg. Run `pnpm nx run island:icons`.', '', 'export const ICON_NAMES = [', ...names.map((name) => ` '${name}',`), '] as const;', '', 'export type IconName = (typeof ICON_NAMES)[number];', '', ].join('\n'), ); return names; }