Add replaceUse plugin - #808
Conversation
|
This is a good plugins! I probably will use it in my project! But Im suggesting to make this plugin being executed before the |
|
@bbqaaq Great call. I almost always run with |
|
Hi, I was testing this plugin and I found several bugs:
|
… outside <defs> This commit also removes referenced nodes if they’re inside <defs> and ultimately removes <defs> if it is empty.
|
@TiagoDinisFonseca I've addressed those bugs. Thanks for reporting them. Regarding the These fixes mean the plugin is no longer complimented by |
|
Unfortunately, this is not true. The tag has some attributes: x, y, height and width that g has not. |
|
As a user I do support adding this plugin as a optional one as I am useful with this. I have gone through this plugin and it works quite fine with the SVGs. |
|
@TiagoDinisFonseca @tshedor any updates here? I'd really like to use this plugin. |
|
I'd guess you should move the attributes from use to the path and not the tag. |
|
@GreLI can we prioritize this? what would you need in order to get this merged? |
|
@lifeiscontent But you can solve it: |
|
Does this need to be absolutely perfect to be considered for addition? This would be very useful for me in it's current state |
|
Rewritten to use the latest csstree api: exports.fn = () => {
const defs = new Map;
const used = new Set;
return {
element: {
enter(node, parentNode) {
if (node.name === 'svg') {
delete node.attributes['xmlns:xlink'];
return
}
if (parentNode.name === 'defs') {
defs.set('#' + node.attributes.id, node);
return;
}
if (node.name === 'use') {
const id = node.attributes.href || node.attributes['xlink:href'];
const def = defs.get(id);
if (!def) {
console.warn(`Could not find definition for ${id}`);
return;
}
delete node.attributes['xlink:href'];
delete node.attributes['href'];
node.name = 'g';
node.children = [...def.children];
used.add(def);
}
},
},
root: {
exit(root) {
const defs = querySelector(root, 'defs');
if (defs) {
defs.children = defs.children.filter(node => !used.has(node));
if (!defs.children.length) {
defs.parentNode.children = defs.parentNode.children.filter(node => node !== defs);
}
}
}
}
}
} |
This plugin replaces all
<use>elements with the nodes they clone and removes the top-levelxlinkattribute. While this doesn't "optimize" the SVG, it allows the contents to be used in SVG sprites within<symbol>elements. This plugin is best used in conjunction with removeUselessDefs.