UNPKG

svg-spritemap-webpack-plugin

Version:

Generates symbol-based SVG spritemap from all .svg files in a directory

54 lines (53 loc) 2.02 kB
import xmldom from '@xmldom/xmldom'; import svgToMiniDataURI from 'mini-svg-data-uri'; import { compact } from 'lodash-es'; // Helpers import { rewriteVariables } from '../variables.js'; import { generatePostfix, generatePrefix, SVG_SERIALIZER } from '../svg.js'; export const formatSelector = (name, location, options) => { return compact([ options.styles.selectors.prefix && generatePrefix(location, options), name ]).join(''); }; export const formatURL = (name, location, svg, options, compilation, rewrite = false) => { switch (options.styles.format) { case 'data': { if (rewrite) { return svgToMiniDataURI(rewriteVariables(SVG_SERIALIZER.serializeToString(svg), (variable) => { return `${variable.attribute}="___${variable.name}___"`; })); } return svgToMiniDataURI(SVG_SERIALIZER.serializeToString(svg)); } case 'fragment': { return compact([ compilation.options.output.publicPath, '#', generatePrefix(location, options), name, generatePostfix(options.sprite.generate.view) ]).join(''); } } }; export const getSymbolSVG = (symbol, options) => { const document = new xmldom.DOMImplementation().createDocument('http://www.w3.org/2000/svg', ''); const svg = document.createElement('svg'); svg.setAttribute('xmlns', 'http://www.w3.org/2000/svg'); if (options.styles.attributes.keep) { [...symbol.attributes].forEach((attribute) => { if (['width', 'height', 'id', 'xmlns'].includes(attribute.name.toLowerCase())) { return; } svg.setAttribute(attribute.name, attribute.value); }); } [...symbol.childNodes].forEach((node) => { if (['title'].includes(node.nodeName.toLowerCase())) { return; } svg.appendChild(node); }); return svg; };