第一步:安装svg-sprite-loader
npm i svg-sprite-loader
第二步:在components目录下创建SvgIcon.vue文件
<template>
<svg :class="svgClass" v-bind="$attrs" :style="{ color: color }">
<use :xlink:href="iconName" rel="external nofollow" />
</svg>
</template>
<script setup>
import { defineProps, computed } from "vue"
const props = defineProps({
name: {
type: String,
required: true
},
color: {
type: String,
default: ""
}
})
const iconName = computed(() => `#icon-${props.name}`)
const svgClass = computed(() => {
console.log(props.name, "props.name")
if (props.name) {
return `svg-icon ${iconName.value}`
}
return "svg-icon"
})
</script>
<style scoped>
.svg-icon {
width: 1em;
height: 1em;
fill: currentColor;
vertical-align: middle;
}
</style>
第三步:在src目录下的assets文件夹下创建svg文件夹,用来存放SVG文件

第四步:在main.ts中将SvgIcon组件全局注册

第五步:在src下新建plugins文件夹,创建svgBuilder.js
import { readFileSync, readdirSync } from "fs";
let idPerfix = "";
const svgTitle = /<svg([^>+].*?)>/;
const clearHeightWidth = /(width|height)="([^>+].*?)"/g;
const hasViewBox = /(viewBox="[^>+].*?")/g;
const clearReturn = /(\r)|(\n)/g;
function findSvgFile(dir) {
const svgRes = [];
const dirents = readdirSync(dir, {
withFileTypes: true,
});
for (const dirent of dirents) {
if (dirent.isDirectory()) {
svgRes.push(...findSvgFile(dir + dirent.name + "/"));
} else {
const svg = readFileSync(dir + dirent.name)
.toString()
.replace(clearReturn, "")
.replace(svgTitle, ($1, $2) => {
let width = 0;
let height = 0;
let content = $2.replace(clearHeightWidth, (s1, s2, s3) => {
if (s2 === "width") {
width = s3;
} else if (s2 === "height") {
height = s3;
}
return "";
});
if (!hasViewBox.test($2)) {
content += `viewBox="0 0 ${width} ${height}"`;
}
return `<symbol id="${idPerfix}-${dirent.name.replace(
".svg",
""
)}" ${content}>`;
})
.replace("</svg>", "</symbol>");
svgRes.push(svg);
}
}
return svgRes;
}
export const svgBuilder = (path, perfix = "icon") => {
if (path === "") return;
idPerfix = perfix;
const res = findSvgFile(path);
return {
name: "svg-transform",
transformIndexHtml(html) {
return html.replace(
"<body>",
`
<body>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="position: absolute; width: 0; height: 0">
${res.join("")}
</svg>
`
);
},
};
};
第六步:在vite.config.ts修改配置

第七步:在项目中使用,name和color必传
