index.ts 1.4 KB

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