UNPKG

vite-plugin-svg-sprite

Version:
55 lines (54 loc) 1.75 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.svgToSymbol = svgToSymbol; const xmldom_1 = require("@xmldom/xmldom"); const micromatch_1 = __importDefault(require("micromatch")); const preserveAttrs = [ 'viewBox', 'preserveAspectRatio', 'class', 'overflow', 'stroke?(-*)', 'fill?(-*)', 'xmlns?(:*)', 'role', 'aria-*', ]; function findSvgNode(doc) { return Array.from(doc.childNodes).find((node) => node.nodeType === doc.ELEMENT_NODE && node.tagName === 'svg'); } function svgToSymbol(xml, id) { const domParser = new xmldom_1.DOMParser(); const doc = domParser.parseFromString(xml.trim(), 'text/xml'); const svg = findSvgNode(doc); if (!svg) { return null; } const symbol = doc.createElement('symbol'); symbol.setAttribute('id', id); Array.from(svg.attributes).forEach((attr) => { if (micromatch_1.default.isMatch(attr.name, preserveAttrs)) { symbol.setAttribute(attr.name, attr.value); } }); Array.from(svg.childNodes).forEach((node) => { symbol.appendChild(node); }); const width = svg.getAttribute('width'); const height = svg.getAttribute('height'); if (!symbol.hasAttribute('viewBox') && width && height) { symbol.setAttribute('viewBox', `0 0 ${width} ${height}`); } const serializer = new xmldom_1.XMLSerializer(); return { symbolXml: serializer.serializeToString(symbol), attributes: { width, height, viewBox: svg.getAttribute('viewBox'), }, }; }