|
| 1 | +const fs = require('fs'); |
| 2 | +const path = require('path'); |
| 3 | +const { execSync } = require('child_process'); |
| 4 | + |
| 5 | +// Directory constants |
| 6 | +const DIRS = { |
| 7 | + RAW_SVGS: path.join(__dirname, '../src/assets/svgs/raw'), |
| 8 | + OPTIMIZED_SVGS: path.join(__dirname, '../src/assets/svgs/optimized'), |
| 9 | + INDEX: path.join(__dirname, '../src/assets/icons/index.ts'), |
| 10 | +}; |
| 11 | + |
| 12 | +/** |
| 13 | + * Clean and recreate the optimized SVGs directory |
| 14 | + */ |
| 15 | +function setupDirectories() { |
| 16 | + if (fs.existsSync(DIRS.OPTIMIZED_SVGS)) { |
| 17 | + fs.rmSync(DIRS.OPTIMIZED_SVGS, { recursive: true, force: true }); |
| 18 | + } |
| 19 | + fs.mkdirSync(DIRS.OPTIMIZED_SVGS, { recursive: true }); |
| 20 | +} |
| 21 | + |
| 22 | +/** |
| 23 | + * Optimize SVGs using SVGO |
| 24 | + */ |
| 25 | +function optimizeSvgs() { |
| 26 | + console.log('\nOptimizing SVGs with SVGO...'); |
| 27 | + try { |
| 28 | + execSync(`npx svgo -rf "${DIRS.RAW_SVGS}" -o "${DIRS.OPTIMIZED_SVGS}"`, { |
| 29 | + stdio: 'inherit', |
| 30 | + }); |
| 31 | + console.log('\nSVG optimization completed successfully!'); |
| 32 | + } catch (error) { |
| 33 | + throw new Error(`SVGO optimization failed: ${error.message}`); |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +/** |
| 38 | + * Generate the icons/index.ts file with optimized SVGs |
| 39 | + */ |
| 40 | +function generateIndexFile() { |
| 41 | + console.log('\nGenerating index.ts...'); |
| 42 | + const optimizedSvgs = fs |
| 43 | + .readdirSync(DIRS.OPTIMIZED_SVGS) |
| 44 | + .filter((file) => file.endsWith('.svg')); |
| 45 | + |
| 46 | + const indexContent = `/** |
| 47 | + * This file is auto-generated. Do not edit it manually. |
| 48 | + * Run \`node scripts/optimize-svgs.js\` to regenerate. |
| 49 | + */ |
| 50 | +
|
| 51 | +${optimizedSvgs |
| 52 | + .map((file) => { |
| 53 | + const name = path.basename(file, '.svg'); |
| 54 | + const svgContent = fs.readFileSync( |
| 55 | + path.join(DIRS.OPTIMIZED_SVGS, file), |
| 56 | + 'utf8', |
| 57 | + ); |
| 58 | + return `export const ${name}Icon = (color = 'white'): string => \`\n${svgContent}\`;`; |
| 59 | + }) |
| 60 | + .join('\n\n')}\n`; |
| 61 | + |
| 62 | + fs.writeFileSync(DIRS.INDEX, indexContent); |
| 63 | + console.log(`Generated index.ts with ${optimizedSvgs.length} icons!`); |
| 64 | +} |
| 65 | + |
| 66 | +function main() { |
| 67 | + try { |
| 68 | + // Setup directories |
| 69 | + setupDirectories(); |
| 70 | + |
| 71 | + // Optimize and generate index |
| 72 | + optimizeSvgs(); |
| 73 | + generateIndexFile(); |
| 74 | + } catch (error) { |
| 75 | + console.error('\nError:', error.message); |
| 76 | + process.exit(1); |
| 77 | + } |
| 78 | +} |
| 79 | + |
| 80 | +main(); |
0 commit comments