下载包
npm install vite-plugin-svg-icons -D
在vite.config.js文件中配置
import { defineConfig } from "vite";
import { createSvgIconsPlugin } from "vite-plugin-svg-icons";
import vue from "@vitejs/plugin-vue";
import * as path from "path";
export default defineConfig({
plugins: [
createSvgIconsPlugin({
// 指定需要缓存的图标文件夹
iconDirs: [path.resolve(process.cwd(), "src/assets/svgs")],
}),
vue(),
],
});
后续所有的svg文件都放在assets/svgs中
image.png
在components中创建svgIcon组件
<template>
<svg>
<use :xlink:href="symbolId" :fill="color" />
</svg>
</template>
<script setup lang="ts">
import { computed } from "vue";
let props = withDefaults(defineProps<{ iconClass: string; color?: string }>(), {
color: "#000",
});
const symbolId = computed(() => `#icon-${props.iconClass}`);
</script>
<style scoped>
svg {
width: 100%;
height: 100%;
}
</style>
在main.js中
import "virtual:svg-icons-register";
import SvgIcon from "./components/svgIcon.vue";
app.component("SvgIcon", SvgIcon);
普通文件中使用
<SvgIcon iconClass="home"></SvgIcon>