1、安装
npm i vite-plugin-svg-icons -D
2、配置svgIcon.vue组件
<template>
<svg aria-hidden="true" :class="svgClass">
<use :xlink:href="symbolId" />
</svg>
</template>
<script setup lang="ts">
import { computed } from "vue";
const props = defineProps({
prefix: {
type: String,
default: "icon",
},
name: {
type: String,
required: true,
},
color: {
type: String,
default: "#333",
},
size: {
type: String,
default: "2em",
},
className: {
type: String,
default: "",
},
});
const symbolId = computed(() => `#${props.prefix}-${props.name}`);
const svgClass = computed(() => {
if (props.className) {
return "svg-icon " + props.className;
} else {
return "svg-icon";
}
});
</script>
<style scoped>
.svg-icon {
width: 1em;
height: 1em;
vertical-align: -0.2em;
fill: currentColor;
overflow: hidden;
}
</style>
3、全局引入
1、 vite.config.ts
import { createSvgIconsPlugin } from "vite-plugin-svg-icons";
.......
plugins: [
vue(),
vueJsx(),
createSvgIconsPlugin({
// iconDirs: [path.resolve(process.cwd(), "src/icons/svg")],
iconDirs: [fileURLToPath(new URL("./src/icons/svg", import.meta.url))],
symbolId: "icon-[name]",
}),
],
2、main.ts
import type { App } from "vue";
import "virtual:svg-icons-register";
import SvgIcon from "@/components/SvgIcon.vue";
export default function (app: App): void {
app.component("SvgIcon", SvgIcon);
}