generate-svg-icons.mjs 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. // 从 @iconify-json/ph 与 @iconify-json/solar 中抽取项目实际用到的图标,
  2. // 生成一个精简的 iconify 数据文件,供 weapp-svg-icon 组件使用,避免全量打包。
  3. //
  4. // 生成结果通过 pnpm patch 写成补丁(patches/weapp-svg-icon@<version>.patch),安装依赖时由 pnpm 自动应用。
  5. // 不能直接改 node_modules 里的文件:pnpm 用硬链接指向全局存储,直接写入会污染其他项目共用的包。
  6. import { execSync } from 'node:child_process'
  7. import { readdir, readFile, rm, writeFile } from 'node:fs/promises'
  8. import { tmpdir } from 'node:os'
  9. import path from 'node:path'
  10. import process from 'node:process'
  11. import { fileURLToPath } from 'node:url'
  12. const __dirname = path.dirname(fileURLToPath(import.meta.url))
  13. const root = path.resolve(__dirname, '..')
  14. const SRC_DIR = path.join(root, 'src')
  15. const PKG_NAME = 'weapp-svg-icon'
  16. const PKG_DIR = path.join(root, 'node_modules', PKG_NAME)
  17. // pnpm patch 取出的可编辑副本。必须放在纯英文路径下:项目路径含中文时,
  18. // git 生成的 diff 会转义路径,pnpm patch-commit 会产出无法应用的补丁。
  19. const EDIT_DIR = path.join(tmpdir(), `${PKG_NAME}-patch`)
  20. // weapp-vite 按 package.json 依赖哈希缓存 npm 构建结果,补丁变化后需清除才会重新复制。
  21. const WEAPP_VITE_NPM_CACHE_DIR = path.join(root, 'node_modules', 'weapp-vite', '.cache')
  22. function pnpm(args) {
  23. // Windows 下 pnpm 是 .cmd 脚本,只能经 shell 执行;参数逐个加引号,避免路径中的空格被拆开。
  24. execSync(['pnpm', ...args.map(arg => `"${arg}"`)].join(' '), { cwd: root, stdio: 'inherit' })
  25. }
  26. const ICON_PREFIXES = ['ph', 'solar']
  27. const ICON_RE = /(?:^|\W)(ph|solar):([a-z0-9-]+)/g
  28. const SCAN_EXTENSIONS = new Set(['.ts', '.js', '.wxml', '.vue', '.json'])
  29. async function walk(dir) {
  30. const entries = await readdir(dir, { withFileTypes: true })
  31. const files = []
  32. for (const entry of entries) {
  33. if (entry.name === 'node_modules' || entry.name.startsWith('.')) {
  34. continue
  35. }
  36. const full = path.join(dir, entry.name)
  37. if (entry.isDirectory()) {
  38. files.push(...(await walk(full)))
  39. }
  40. else {
  41. files.push(full)
  42. }
  43. }
  44. return files
  45. }
  46. async function collectUsedIcons() {
  47. const files = await walk(SRC_DIR)
  48. const used = new Set()
  49. for (const file of files) {
  50. if (!SCAN_EXTENSIONS.has(path.extname(file))) {
  51. continue
  52. }
  53. const content = await readFile(file, 'utf8')
  54. for (const match of content.matchAll(ICON_RE)) {
  55. used.add(`${match[1]}:${match[2]}`)
  56. }
  57. }
  58. return [...used].sort()
  59. }
  60. async function loadIconifyJson(packageName) {
  61. const p = path.join(root, 'node_modules', '@iconify-json', packageName, 'icons.json')
  62. return JSON.parse(await readFile(p, 'utf8'))
  63. }
  64. async function main() {
  65. const used = await collectUsedIcons()
  66. const byPrefix = { ph: new Set(), solar: new Set() }
  67. for (const id of used) {
  68. const [prefix, icon] = id.split(':')
  69. byPrefix[prefix]?.add(icon)
  70. }
  71. const sets = {}
  72. const svgNameSwitch = id =>
  73. id
  74. .split(/[:\-_]/)
  75. .filter(Boolean)
  76. .map(s => s[0].toUpperCase() + s.slice(1).toLowerCase())
  77. .join('')
  78. for (const prefix of ICON_PREFIXES) {
  79. const source = await loadIconifyJson(prefix)
  80. const icons = {}
  81. for (const icon of [...byPrefix[prefix]].sort()) {
  82. if (source.icons[icon]) {
  83. icons[icon] = source.icons[icon]
  84. }
  85. }
  86. sets[svgNameSwitch(prefix)] = {
  87. prefix: source.prefix ?? prefix,
  88. width: source.width,
  89. height: source.height,
  90. icons,
  91. }
  92. }
  93. const template = `// Generated by scripts/generate-svg-icons.mjs — DO NOT EDIT.
  94. // Minimal iconify data extracted from @iconify-json/ph + @iconify-json/solar.
  95. var iconifyPresets = ${JSON.stringify(sets)}
  96. function svgNameSwitch(id) {
  97. return id
  98. .split(/:|-|_/)
  99. .filter(Boolean)
  100. .map(function (s) {
  101. return s[0].toUpperCase() + s.slice(1).toLowerCase()
  102. })
  103. .join('')
  104. }
  105. function encodeSvg(svg) {
  106. return svg
  107. .replace('<svg', ~svg.indexOf('xmlns') ? '<svg' : '<svg xmlns="http://www.w3.org/2000/svg"')
  108. .replace(/"/g, "'")
  109. .replace(/%/g, '%25')
  110. .replace(/#/g, '%23')
  111. .replace(/{/g, '%7B')
  112. .replace(/}/g, '%7D')
  113. .replace(/</g, '%3C')
  114. .replace(/>/g, '%3E')
  115. }
  116. function getDataUri(data) {
  117. return 'url("data:image/svg+xml;utf8,' + data + '")'
  118. }
  119. function presetsIconify(id) {
  120. var parts = id.split(':')
  121. var prefix = ''
  122. var icon = ''
  123. if (parts.length === 2) {
  124. prefix = svgNameSwitch(parts[0])
  125. icon = parts[1]
  126. } else if (parts.length === 1) {
  127. parts = parts[0].split('-')
  128. if (parts.length > 1) {
  129. prefix = svgNameSwitch(parts.shift())
  130. icon = parts.join('-')
  131. }
  132. }
  133. var setData = iconifyPresets[prefix] || null
  134. var width = setData && setData.width ? setData.width : 32
  135. var height = setData && setData.height ? setData.height : 32
  136. var iconData = setData && setData.icons && setData.icons[icon] ? setData.icons[icon] : null
  137. if (!iconData) {
  138. return ''
  139. }
  140. var svgAttributes = {
  141. xmlns: 'http://www.w3.org/2000/svg',
  142. 'xmlns:xlink': 'http://www.w3.org/1999/xlink',
  143. width: '1em',
  144. height: '1em',
  145. preserveAspectRatio: 'xMidYMid meet',
  146. viewBox: '0 0 ' + width + ' ' + height
  147. }
  148. var svgAttributesStr = Object.keys(svgAttributes)
  149. .map(function (attr) {
  150. return attr + '="' + svgAttributes[attr] + '"'
  151. })
  152. .join(' ')
  153. return '<svg ' + svgAttributesStr + '>' + iconData.body + '</svg>'
  154. }
  155. function getLocalSVG(id) {
  156. var name = svgNameSwitch(id)
  157. var data = presetsIconify(id)
  158. if (data) {
  159. return getDataUri(encodeSvg(data))
  160. }
  161. data = wx.getStorageSync(name)
  162. if (data) {
  163. return getDataUri(data)
  164. }
  165. return ''
  166. }
  167. Component({
  168. properties: {
  169. name: {
  170. type: String,
  171. value: ''
  172. },
  173. color: {
  174. type: String,
  175. value: ''
  176. },
  177. size: {
  178. type: String
  179. }
  180. },
  181. data: {
  182. width: '1em',
  183. height: '1em',
  184. iconUrl: '',
  185. class: ''
  186. },
  187. lifetimes: {
  188. attached: function attached() {
  189. this.setData({
  190. iconUrl: getLocalSVG(this.data.name),
  191. class: this.data.color ? 'icon' : 'default-icon'
  192. })
  193. if (this.data.size) {
  194. this.setData({
  195. width: this.data.size,
  196. height: this.data.size
  197. })
  198. }
  199. }
  200. }
  201. })
  202. `
  203. const { version } = JSON.parse(await readFile(path.join(PKG_DIR, 'package.json'), 'utf8'))
  204. await rm(EDIT_DIR, { recursive: true, force: true })
  205. // 每次都从原版包重新生成整份文件,不叠加已有补丁。
  206. pnpm(['patch', `${PKG_NAME}@${version}`, '--edit-dir', EDIT_DIR, '--ignore-existing'])
  207. await writeFile(path.join(EDIT_DIR, 'miniprogram_dist', 'index.js'), template, 'utf8')
  208. // 原 source map 对应的是被替换掉的打包代码,一并删除。
  209. await rm(path.join(EDIT_DIR, 'miniprogram_dist', 'index.js.map'), { force: true })
  210. pnpm(['patch-commit', EDIT_DIR])
  211. await rm(EDIT_DIR, { recursive: true, force: true })
  212. const cacheFiles = await readdir(WEAPP_VITE_NPM_CACHE_DIR).catch(() => [])
  213. await Promise.all(cacheFiles.filter(file => file.endsWith('.json')).map(file => rm(path.join(WEAPP_VITE_NPM_CACHE_DIR, file), { force: true })))
  214. console.log(`generated ${PKG_NAME} patch with ${used.length} icons`)
  215. console.log(used.join('\n'))
  216. }
  217. main().catch((err) => {
  218. console.error(err)
  219. process.exit(1)
  220. })