- svg内部的 xhref ji strokle 属性都在通过id选择器在引用内部标签,这就导致了如果不小心多个svg里面源码id标记重复了,就直接导致内部渲染引用的标签是非自身的,导致渲染错误,这个时候通过手动修改标签里面所有id 拼接上一个独有名称形成唯一ID。
原本以为这样就结束了,但是想到如果下次这类问题,怎么自动化解决,想到了jscodeshfit。 直接批量源码级别替换。
const j = api.jscodeshift;
// 将SVG文件解析为AST
const ast = j(file.source);
// 要处理的属性名称列表
const attributesToProcess = ["stroke", "xlink:href"];
// 处理每个属性
attributesToProcess.forEach((attributeName) => {
ast.find(j.JSXAttribute, { name: { name: attributeName } }).forEach((path) => {
const attributeValue = path.node.value;
if (attributeValue && attributeValue.type === "StringLiteral") {
// 添加唯一的后缀字符
attributeValue.value = attributeValue.value + "_unique";
}
});
});
// 将AST转换回代码
return ast.toSource();
}