|
| 1 | +import { readFileSync } from "fs"; |
| 2 | +import { transform } from "esbuild"; |
| 3 | +import { Plugin } from "vite"; |
| 4 | + |
| 5 | +export default function svgPlugin(): Plugin { |
| 6 | + return { |
| 7 | + name: "svg", |
| 8 | + enforce: "pre", |
| 9 | + load(id) { |
| 10 | + if (id.endsWith(".svg")) { |
| 11 | + return readFileSync(id, "utf-8"); |
| 12 | + } |
| 13 | + if (id.endsWith(".svg?inline")) { |
| 14 | + return readFileSync(id.replace("?inline", ""), "utf-8"); |
| 15 | + } |
| 16 | + }, |
| 17 | + transform(code, id) { |
| 18 | + if (id.endsWith(".svg")) { |
| 19 | + return transform(svgToJSX(code), { loader: "jsx" }); |
| 20 | + } |
| 21 | + if (id.endsWith(".svg?inline")) { |
| 22 | + const base64 = Buffer.from(code).toString("base64"); |
| 23 | + return `export default "data:image/svg+xml;base64,${base64}"`; |
| 24 | + } |
| 25 | + }, |
| 26 | + }; |
| 27 | +} |
| 28 | + |
| 29 | +const svgToJSX = (svg: string) => |
| 30 | + `import React from "react";const ReactComponent = (props) => (${svg |
| 31 | + .replace(/\s([a-z-:]*)="[^"]*"/gu, (string, key: string) => { |
| 32 | + if (key.startsWith("data-")) return string; |
| 33 | + const keyWithoutDashes = camelCaseOn(key, "-"); |
| 34 | + const keyWithoutDots = camelCaseOn(keyWithoutDashes, ":"); |
| 35 | + return string.replace(key, keyWithoutDots); |
| 36 | + }) |
| 37 | + .replace(">", " {...props}>")});export default ReactComponent`; |
| 38 | + |
| 39 | +const camelCaseOn = (string: string, delimiter: string) => |
| 40 | + string |
| 41 | + .split(delimiter) |
| 42 | + .map((v, i) => (i === 0 ? v : v[0].toUpperCase() + v.slice(1))) |
| 43 | + .join(""); |
0 commit comments