build-icons.mjs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. import fs from 'fs-extra'
  2. import path from 'path'
  3. import { PACKAGES_DIR, getAliases, toPascalCase, getAllIcons } from './helpers.mjs'
  4. import { stringify } from 'svgson'
  5. /**
  6. * Build icons
  7. *
  8. * @param name
  9. * @param componentTemplate
  10. * @param indexIconTemplate
  11. * @param indexTypeTemplate
  12. * @param extension
  13. * @param pretty
  14. */
  15. export const buildJsIcons = ({
  16. name,
  17. componentTemplate,
  18. indexItemTemplate,
  19. aliasTemplate,
  20. extension = 'js',
  21. key = true,
  22. pascalCase = false,
  23. pascalName = true,
  24. indexFile = 'icons.ts'
  25. }) => {
  26. const DIST_DIR = path.resolve(PACKAGES_DIR, name);
  27. const aliases = getAliases(),
  28. allIcons = getAllIcons(false, true)
  29. let index = []
  30. Object.entries(allIcons).forEach(([type, icons]) => {
  31. icons.forEach((icon, i) => {
  32. process.stdout.write(`Building \`${name}\` ${type} ${i}/${icons.length}: ${icon.name.padEnd(42)}\r`)
  33. const children = icon.obj.children
  34. .map(({
  35. name,
  36. attributes
  37. }, i) => {
  38. if (key) {
  39. attributes.key = `svg-${i}`
  40. }
  41. if (pascalCase) {
  42. attributes.strokeWidth = attributes['stroke-width']
  43. delete attributes['stroke-width']
  44. }
  45. return [name, attributes]
  46. })
  47. .filter((i) => {
  48. const [name, attributes] = i
  49. return !attributes.d || attributes.d !== 'M0 0h24v24H0z'
  50. })
  51. const iconName = `${icon.name}${type !== 'outline' ? `-${type}` : ''}`,
  52. iconNamePascal = `${icon.namePascal}${type !== 'outline' ? toPascalCase(type) : ''}`
  53. let component = componentTemplate({
  54. type,
  55. name: iconName,
  56. namePascal: iconNamePascal,
  57. children,
  58. stringify,
  59. svg: icon.content
  60. })
  61. let filePath = path.resolve(DIST_DIR, 'src/icons', `${pascalName ? iconNamePascal : iconName}.${extension}`)
  62. fs.writeFileSync(filePath, component, 'utf-8')
  63. index.push(indexItemTemplate({
  64. type,
  65. name: iconName,
  66. namePascal: iconNamePascal
  67. }))
  68. })
  69. })
  70. fs.writeFileSync(path.resolve(DIST_DIR, `src/icons/${indexFile}`), index.join('\n'), 'utf-8')
  71. // Write aliases
  72. let aliasesStr = '';
  73. if (aliases && aliasTemplate) {
  74. Object.entries(aliases).forEach(([from, to]) => {
  75. aliasesStr += aliasTemplate({
  76. from,
  77. to,
  78. fromPascal: toPascalCase(from),
  79. toPascal: toPascalCase(to)
  80. })
  81. })
  82. }
  83. fs.writeFileSync(path.resolve(DIST_DIR, `./src/aliases.ts`), aliasesStr || `export {};`, 'utf-8')
  84. }