svgIcon.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import { readFileSync, readdirSync } from 'fs'
  2. const svgTitle = /<svg([^>+].*?)>/
  3. const clearHeightWidth = /(width|height)="([^>+].*?)"/g
  4. const hasViewBox = /(viewBox="[^>+].*?")/g
  5. const clearReturn = /(\r)|(\n)/g
  6. function findSvgFile(dir) {
  7. const svgRes = []
  8. const dirents = readdirSync(dir, {
  9. withFileTypes: true
  10. })
  11. for (const dirent of dirents) {
  12. if (dirent.isDirectory()) {
  13. svgRes.push(...findSvgFile(dir + dirent.name + '/'))
  14. } else {
  15. const svg = readFileSync(dir + dirent.name)
  16. .toString()
  17. .replace(clearReturn, '')
  18. .replace(svgTitle, ($1, $2) => {
  19. let width = 0
  20. let height = 0
  21. let content = $2.replace(clearHeightWidth, (s1, s2, s3) => {
  22. if (s2 === 'width') {
  23. width = s3
  24. } else if (s2 === 'height') {
  25. height = s3
  26. }
  27. return ''
  28. })
  29. if (!hasViewBox.test($2)) {
  30. content += `viewBox="0 0 ${width} ${height}"`
  31. }
  32. return `<symbol id="${dirent.name.replace('.svg', '')}" ${content}>`
  33. })
  34. .replace('</svg>', '</symbol>')
  35. svgRes.push(svg)
  36. }
  37. }
  38. return svgRes
  39. }
  40. export const svgBuilder = (path) => {
  41. if (path === '') return
  42. const res = findSvgFile(path)
  43. return {
  44. name: 'svg-transform',
  45. transformIndexHtml(html) {
  46. return html.replace(
  47. '<body>',
  48. `
  49. <body>
  50. <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="position: absolute; width: 0; height: 0">
  51. ${res.join('')}
  52. </svg>
  53. `
  54. )
  55. }
  56. }
  57. }