1*5589cdf3S猫头猫import fs from 'fs/promises'; 2*5589cdf3S猫头猫import path from 'path'; 3*5589cdf3S猫头猫import * as url from "node:url"; 4*5589cdf3S猫头猫 5*5589cdf3S猫头猫 6*5589cdf3S猫头猫function toCamelCase(str) { 7*5589cdf3S猫头猫 // 将下划线和中划线统一替换为空格 8*5589cdf3S猫头猫 let camelCaseStr = str.replace(/[-_]/g, ' '); 9*5589cdf3S猫头猫 10*5589cdf3S猫头猫 // 将每个单词的首字母大写,其余字母小写 11*5589cdf3S猫头猫 camelCaseStr = camelCaseStr.split(' ').map(word => { 12*5589cdf3S猫头猫 return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase(); 13*5589cdf3S猫头猫 }).join(''); 14*5589cdf3S猫头猫 15*5589cdf3S猫头猫 return camelCaseStr; 16*5589cdf3S猫头猫} 17*5589cdf3S猫头猫 18*5589cdf3S猫头猫// 读取所有的icon 19*5589cdf3S猫头猫const basePath = path.resolve(url.fileURLToPath(import.meta.url), '../../src/assets/icons') 20*5589cdf3S猫头猫 21*5589cdf3S猫头猫// 读取所有的svg 22*5589cdf3S猫头猫const icons = await fs.readdir(basePath) 23*5589cdf3S猫头猫 24*5589cdf3S猫头猫const assets = icons.map(it => ({ 25*5589cdf3S猫头猫 componentName: toCamelCase(it.slice(0, -path.extname(it).length)) + "Icon", 26*5589cdf3S猫头猫 filePath: `@/assets/icons/${it}`, 27*5589cdf3S猫头猫 name: it.slice(0, -path.extname(it).length) 28*5589cdf3S猫头猫})) 29*5589cdf3S猫头猫 30*5589cdf3S猫头猫let scriptTemplate = `// This file is generated by generate-assets.mjs. DO NOT MODIFY. 31*5589cdf3S猫头猫import {SvgProps} from 'react-native-svg'; 32*5589cdf3S猫头猫 33*5589cdf3S猫头猫${assets.map(asset => `import ${asset.componentName} from '${asset.filePath}';`).join('\n')} 34*5589cdf3S猫头猫 35*5589cdf3S猫头猫export type IIconName = ${assets.map(asset => `'${asset.name}'`).join(' | ')}; 36*5589cdf3S猫头猫 37*5589cdf3S猫头猫interface IProps extends SvgProps { 38*5589cdf3S猫头猫 /** 图标名称 */ 39*5589cdf3S猫头猫 name: IIconName; 40*5589cdf3S猫头猫 /** 图标大小 */ 41*5589cdf3S猫头猫 size?: number; 42*5589cdf3S猫头猫} 43*5589cdf3S猫头猫 44*5589cdf3S猫头猫const iconMap = { 45*5589cdf3S猫头猫${assets.map(asset => ` '${asset.name}': ${asset.componentName}`).join(',\n')} 46*5589cdf3S猫头猫} as const; 47*5589cdf3S猫头猫 48*5589cdf3S猫头猫export default function Icon(props: IProps) { 49*5589cdf3S猫头猫 const {name, size} = props; 50*5589cdf3S猫头猫 51*5589cdf3S猫头猫 const newProps = { 52*5589cdf3S猫头猫 ...props, 53*5589cdf3S猫头猫 width: props.width ?? size, 54*5589cdf3S猫头猫 height: props.width ?? size 55*5589cdf3S猫头猫 } as SvgProps; 56*5589cdf3S猫头猫 57*5589cdf3S猫头猫 const Component = iconMap[name]; 58*5589cdf3S猫头猫 59*5589cdf3S猫头猫 return <Component {...newProps}></Component>; 60*5589cdf3S猫头猫} 61*5589cdf3S猫头猫` 62*5589cdf3S猫头猫 63*5589cdf3S猫头猫const targetPath = path.resolve(url.fileURLToPath(import.meta.url), '../../src/components/base/icon.tsx'); 64*5589cdf3S猫头猫await fs.writeFile(targetPath, scriptTemplate, 'utf8'); 65*5589cdf3S猫头猫 66*5589cdf3S猫头猫console.log(`Generate Succeed. ${assets.length} assets.`)