SVGLoader.ts 2.1 KB

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