import path from 'node:path'; import prettier from 'prettier'; import * as svgson from 'svgson'; import { kebabToCamel, kebabToPascal, readSvg, writeFile } from './helper'; async function getSvgAstInfo(svg: string) { const svgAst = await svgson.parse(svg); if (!svgAst.children.length) { throw new Error('❌ Not found svg content'); } return svgAst.children.map(node => { const attributes = Object.fromEntries( Object.entries(node.attributes).map(([key, value]) => [ kebabToCamel(key), value, ]), ); return { attributes, name: node.name }; }); } interface GenerateSVGIconOptions { source: string; output: string; category: string; } export async function generateSvgIcon(options: GenerateSVGIconOptions) { const svg = await readSvg(options.source); const svgInfo = await getSvgAstInfo(svg); const template = ` import { createSvgIcon } from "../create-svg-icon"; export default createSvgIcon(${JSON.stringify(svgInfo)}) `; const output = await prettier.format(template, { parser: 'typescript', tabWidth: 2, printWidth: 120, singleQuote: true, trailingComma: 'all', }); const basename = path.basename(options.source, '.svg'); const filename = `${basename}-${options.category}`; const outputSvgFile = path.resolve(options.output, `${filename}.ts`); await writeFile(outputSvgFile, output); return [kebabToPascal(filename), filename]; }