svgBuilder.ts 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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. // Find the svg file
  8. function svgFind(e) {
  9. const arr = []
  10. const dirents = readdirSync(e, { withFileTypes: true })
  11. for (const dirent of dirents) {
  12. if (dirent.isDirectory()) arr.push(...svgFind(e + dirent.name + '/'))
  13. else {
  14. const svg = readFileSync(e + dirent.name)
  15. .toString()
  16. .replace(clearReturn, '')
  17. .replace(svgTitle, ($1, $2) => {
  18. let width = 0
  19. let height = 0
  20. let content = $2.replace(clearHeightWidth, (s1, s2, s3) => {
  21. if (s2 === 'width') width = s3
  22. else if (s2 === 'height') height = s3
  23. return ''
  24. })
  25. if (!hasViewBox.test($2)) content += `viewBox="0 0 ${width} ${height}"`
  26. return `<symbol id="${idPerfix}-${dirent.name.replace('.svg', '')}" ${content}>`
  27. }).replace('</svg>', '</symbol>')
  28. arr.push(svg)
  29. }
  30. }
  31. return arr
  32. }
  33. export const svgBuilder = (path: any, perfix = 'icon') => {
  34. if (path === '') return
  35. idPerfix = perfix
  36. const res = svgFind(path)
  37. console.log(res)
  38. return {
  39. name: 'svg-transform',
  40. transformIndexHtml (dom: String) {
  41. return dom.replace(
  42. '<body>',
  43. `<body><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="position: absolute; width: 0; height: 0" version="1.1">${res.join('')}</svg>`
  44. )
  45. }
  46. }
  47. }