generate.icons.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import path from 'node:path'
  2. import fs from 'fs-extra'
  3. import inquirer from 'inquirer'
  4. import { lookupCollection, lookupCollections } from '@iconify/json'
  5. async function generateIcons() {
  6. // 拿到全部图标集的原始数据
  7. const raw = await lookupCollections()
  8. // 默认必须安装的图标集
  9. const defaultCollectionID = ['ep']
  10. // 取出可使用的图标集数据用于 inquirer 选择,并按名称排序
  11. const collections = Object.entries(raw).map(([id, item]) => ({
  12. ...item,
  13. id,
  14. })).filter((item) => {
  15. return item.hidden !== true && !defaultCollectionID.includes(item.id)
  16. }).sort((a, b) => a.name.localeCompare(b.name))
  17. /**
  18. * 分别会在对应目录下生成以下文件,其中(1)(3)用于离线下载并安装图标,(2)用于图标选择器使用
  19. * (1) src/iconify/index.json 记录用户 inquirer 的交互信息
  20. * (2) src/iconify/data.json 包含多个图标集数据,仅记录图标名
  21. * (3) public/icons/*-raw.json 多个图标集的原始数据,独立存放,用于离线使用
  22. */
  23. inquirer.prompt([
  24. {
  25. type: 'checkbox',
  26. message: '请选择需要生成的图标集',
  27. name: 'collections',
  28. choices: collections.map(item => ({
  29. name: `${item.name} (${item.total} icons)`,
  30. value: item.id,
  31. })),
  32. },
  33. {
  34. type: 'list',
  35. message: '图标集使用方式',
  36. name: 'useType',
  37. choices: [
  38. { name: '在线', value: 'online', default: true },
  39. { name: '离线 (本地)', value: 'offline' },
  40. ],
  41. },
  42. ]).then(async (answers) => {
  43. answers.collections.push(...defaultCollectionID)
  44. await fs.writeJSON(
  45. path.resolve(process.cwd(), 'src/iconify/index.json'),
  46. {
  47. collections: answers.collections,
  48. useType: answers.useType,
  49. },
  50. )
  51. const outputDir = path.resolve(process.cwd(), 'public/icons')
  52. await fs.ensureDir(outputDir)
  53. await fs.emptyDir(outputDir)
  54. const collectionsMeta: object[] = []
  55. for (const info of answers.collections) {
  56. const setData = await lookupCollection(info)
  57. collectionsMeta.push({
  58. prefix: setData.prefix,
  59. info: setData.info,
  60. icons: Object.keys(setData.icons),
  61. })
  62. const offlineFilePath = path.join(outputDir, `${info}-raw.json`)
  63. if (answers.useType === 'offline') {
  64. await fs.writeJSON(offlineFilePath, setData)
  65. }
  66. }
  67. await fs.writeJSON(
  68. path.resolve(process.cwd(), 'src/iconify/data.json'),
  69. collectionsMeta,
  70. )
  71. })
  72. }
  73. generateIcons()