|
| 1 | +import path from "path"; |
| 2 | +import fs from "fs/promises"; |
| 3 | +import glob from "fast-glob"; |
| 4 | +import { optimize } from "svgo"; |
| 5 | +import Mustache from "mustache"; |
| 6 | + |
| 7 | +async function ensureDir(dir: string): Promise<void> { |
| 8 | + try { |
| 9 | + await fs.mkdir(dir, { recursive: true }); |
| 10 | + } catch (err) { |
| 11 | + if ((err as NodeJS.ErrnoException).code !== "EEXIST") { |
| 12 | + throw err; |
| 13 | + } |
| 14 | + } |
| 15 | +} |
| 16 | + |
| 17 | +function extractSvgInnerContent(svg: string): string { |
| 18 | + const match = svg.match(/<svg[^>]*>([\s\S]*?)<\/svg>/); |
| 19 | + if (!match) { |
| 20 | + throw new Error("Invalid SVG: cannot extract content"); |
| 21 | + } |
| 22 | + return match[1].trim(); |
| 23 | +} |
| 24 | + |
| 25 | +async function cleanSvgContent(svgData: string): Promise<string> { |
| 26 | + const result = optimize(svgData, { |
| 27 | + multipass: true, |
| 28 | + floatPrecision: 3, |
| 29 | + plugins: [ |
| 30 | + "removeComments", |
| 31 | + "removeMetadata", |
| 32 | + "removeTitle", |
| 33 | + "removeDesc", |
| 34 | + "removeUselessDefs", |
| 35 | + "removeEmptyAttrs", |
| 36 | + "removeHiddenElems", |
| 37 | + "removeEmptyText", |
| 38 | + "convertShapeToPath", |
| 39 | + "convertColors", |
| 40 | + "cleanupAttrs", |
| 41 | + "minifyStyles" |
| 42 | + ] |
| 43 | + }); |
| 44 | + |
| 45 | + if ("data" in result) { |
| 46 | + return result.data |
| 47 | + .replace(/fill-opacity=/g, "fillOpacity=") |
| 48 | + .replace(/clip-rule=/g, "clipRule=") |
| 49 | + .replace(/fill-rule=/g, "fillRule=") |
| 50 | + .replace(/stroke-linecap=/g, "strokeLinecap=") |
| 51 | + .replace(/stroke-linejoin=/g, "strokeLinejoin=") |
| 52 | + .replace(/stroke-width=/g, "strokeWidth=") |
| 53 | + .replace(/xlink:href=/g, "xlinkHref="); |
| 54 | + } |
| 55 | + |
| 56 | + throw new Error("SVGO optimization failed"); |
| 57 | +} |
| 58 | + |
| 59 | +function pascalCaseName(filename: string): string { |
| 60 | + return filename |
| 61 | + .replace(/\.svg$/, "") |
| 62 | + .split(/[\s-_]+/) |
| 63 | + .map(s => s.charAt(0).toUpperCase() + s.slice(1)) |
| 64 | + .join(""); |
| 65 | +} |
| 66 | + |
| 67 | +async function generateComponent(svgPath: string, outputDir: string): Promise<string> { |
| 68 | + const svgName = path.basename(svgPath); |
| 69 | + const componentName = pascalCaseName(svgName); |
| 70 | + const outputFileName = svgName.replace(/\.svg$/, ".tsx"); |
| 71 | + |
| 72 | + const svgData = await fs.readFile(svgPath, "utf8"); |
| 73 | + const cleanedSvg = extractSvgInnerContent(await cleanSvgContent(svgData)); |
| 74 | + |
| 75 | + const template = `import React from 'react'; |
| 76 | +import { createIcon } from './utils/IconWrapper'; |
| 77 | +
|
| 78 | +export default createIcon( |
| 79 | + <> |
| 80 | + {{& svgContent }} |
| 81 | + </>, |
| 82 | + "{{componentName}}" |
| 83 | +); |
| 84 | +`; |
| 85 | + |
| 86 | + const componentCode = Mustache.render(template, { |
| 87 | + componentName, |
| 88 | + svgContent: cleanedSvg |
| 89 | + }); |
| 90 | + |
| 91 | + const outPath = path.join(outputDir, outputFileName); |
| 92 | + await ensureDir(path.dirname(outPath)); |
| 93 | + await fs.writeFile(outPath, componentCode, "utf8"); |
| 94 | + return outPath; |
| 95 | +} |
| 96 | + |
| 97 | +async function generateIndex(outputDir: string): Promise<string> { |
| 98 | + const files = await glob(`${outputDir}/*.tsx`); |
| 99 | + const filePath = path.join(outputDir, "index.ts"); |
| 100 | + |
| 101 | + const exports = files |
| 102 | + .map(f => { |
| 103 | + const base = path.basename(f, ".tsx"); |
| 104 | + return `export { default as ${pascalCaseName(base)} } from './${base}';`; |
| 105 | + }) |
| 106 | + .join("\n"); |
| 107 | + |
| 108 | + await fs.writeFile(filePath, exports); |
| 109 | + return filePath; |
| 110 | +} |
| 111 | + |
| 112 | +async function generateTypes(outputDir: string): Promise<string> { |
| 113 | + const files = await glob(`${outputDir}/*.tsx`); |
| 114 | + const iconNames = files.map(f => pascalCaseName(path.basename(f, ".tsx"))); |
| 115 | + const filePath = path.join(outputDir, "index.d.ts"); |
| 116 | + |
| 117 | + const header = `import { IconWrapper } from './utils/IconWrapper';\n\ntype SvgIconComponent = typeof IconWrapper;\n\n`; |
| 118 | + const lines = iconNames.map(name => `export const ${name}: SvgIconComponent;`); |
| 119 | + |
| 120 | + const content = `${header}${lines.join("\n")}\n`; |
| 121 | + |
| 122 | + await fs.writeFile(filePath, content, "utf8"); |
| 123 | + return filePath; |
| 124 | +} |
| 125 | + |
| 126 | +export async function build(srcDir: string, outDir: string): Promise<string[]> { |
| 127 | + await ensureDir(outDir); |
| 128 | + const files = []; |
| 129 | + |
| 130 | + const svgFiles = await glob(`${srcDir}/**/*.svg`); |
| 131 | + |
| 132 | + for (const svgPath of svgFiles) { |
| 133 | + files.push(await generateComponent(svgPath, outDir)); |
| 134 | + } |
| 135 | + |
| 136 | + files.push(await generateIndex(outDir)); |
| 137 | + files.push(await generateTypes(outDir)); |
| 138 | + return files; |
| 139 | +} |
| 140 | + |
| 141 | +export async function main(argv: string[]) { |
| 142 | + if (argv.length < 2) { |
| 143 | + console.error("Usage: node build-icons.js <source-svg-folder> <output-icon-folder>"); |
| 144 | + process.exit(1); |
| 145 | + } |
| 146 | + |
| 147 | + const [srcDir, outDir] = argv; |
| 148 | + |
| 149 | + try { |
| 150 | + await build(srcDir, outDir); |
| 151 | + } catch (err) { |
| 152 | + process.exit(1); |
| 153 | + } |
| 154 | +} |
| 155 | + |
| 156 | +if (require.main === module) { |
| 157 | + main(process.argv.slice(2)); |
| 158 | +} |
0 commit comments