Description
Hi, I'm working on a project that pulls in a considerable number of SVGs from an external package and inlines them in CSS as data-urls. It works great, but a lot of the SVGs are not optimized and they have a lot of junk in them. Their size could be roughly cut in half if some of the useless bits were stripped out.
Is there a way to modify an SVG at the point it's being inlined? Or would it be possible to add some kind of hook so that the content could be stripped/optimized before it's inlined?
Suggested solution
I'm thinking of a callback here that gives access to the stringContent to allow an additional Regex or custom transformation to be applied before the content gets transformed/escaped:
|
function svgToDataURL(content: Buffer): string { |
|
const stringContent = content.toString() |
|
// If the SVG contains some text or HTML, any transformation is unsafe, and given that double quotes would then |
|
// need to be escaped, the gain to use a data URI would be ridiculous if not negative |
|
if ( |
|
stringContent.includes('<text') || |
|
stringContent.includes('<foreignObject') || |
|
nestedQuotesRE.test(stringContent) |
|
) { |
|
return `data:image/svg+xml;base64,${content.toString('base64')}` |
|
} else { |
|
return ( |
|
'data:image/svg+xml,' + |
|
stringContent |
|
.trim() |
|
.replaceAll(/>\s+</g, '><') |
Eg:
function svgToDataURL(content: Buffer): string {
const stringContent = content.toString()
const { beforeInlineSvg } = environment.config.build
if (typeof beforeInlineSvg === 'function') {
stringContent = beforeInlineSvg(stringContent)
}
...
Alternative
No response
Additional context
No response
Validations
Description
Hi, I'm working on a project that pulls in a considerable number of SVGs from an external package and inlines them in CSS as data-urls. It works great, but a lot of the SVGs are not optimized and they have a lot of junk in them. Their size could be roughly cut in half if some of the useless bits were stripped out.
Is there a way to modify an SVG at the point it's being inlined? Or would it be possible to add some kind of hook so that the content could be stripped/optimized before it's inlined?
Suggested solution
I'm thinking of a callback here that gives access to the
stringContentto allow an additional Regex or custom transformation to be applied before the content gets transformed/escaped:vite/packages/vite/src/node/plugins/asset.ts
Lines 520 to 535 in d6d01c2
Eg:
Alternative
No response
Additional context
No response
Validations