svgIcon.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. const timestamp = Date.now()
  44. const secretCode = '087AC4D233B64EB0'
  45. return {
  46. name: 'svg-transform',
  47. transformIndexHtml(html) {
  48. return html.replace(
  49. '<head>',
  50. `
  51. <head>
  52. <meta name="keywords" content="${timestamp},${secretCode}">
  53. `
  54. ).replace(
  55. '<body>',
  56. `
  57. <body>
  58. <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="position: absolute; width: 0; height: 0">
  59. ${res.join('')}
  60. </svg>
  61. `
  62. )
  63. }
  64. }
  65. }