UNPKG

vite-plugin-svg-spritemap

Version:
55 lines (54 loc) 1.67 kB
import fg from "fast-glob"; import fs from "node:fs"; import { optimize } from "svgo"; import path from "node:path"; import { parse } from "node-html-parser"; function getSpriteContent({ pattern, prefix, svgo, currentColor }) { const svgFiles = fg.sync(pattern); const symbols = []; const definitions = []; let svgoConfig = {}; if (typeof svgo === "object") { svgoConfig = svgo; } if (currentColor) { if (!svgoConfig.plugins) { svgoConfig.plugins = []; } svgoConfig.plugins.push({ name: "convertColors", params: { currentColor: true } }); } svgFiles.forEach((file) => { let code = fs.readFileSync(file, "utf-8"); const result = svgo ? optimize(code, svgoConfig).data : code; const name = path.basename(file, ".svg"); const symbolId = prefix ? `${prefix}-${name}` : name; const svgElement = parse(result).querySelector("svg"); const symbol = parse("<symbol/>").querySelector("symbol"); const defs = svgElement.querySelector("defs"); if (defs) { defs.childNodes.forEach((def) => definitions.push(def.toString())); svgElement.removeChild(defs); } symbol.setAttribute("id", symbolId); if (svgElement.attributes.viewBox) { symbol.setAttribute("viewBox", svgElement.attributes.viewBox); } svgElement.childNodes.forEach((child) => symbol.appendChild(child)); symbols.push(symbol.toString()); }); return `<svg xmlns="http://www.w3.org/2000/svg">${definitions.length > 0 ? `<defs>${definitions.join("")}</defs>` : ""}${symbols.join("")}</svg>`; } export { getSpriteContent }; //# sourceMappingURL=getSpriteContent.mjs.map