1.新建svg目录 assets/svg
2.安装插件 npm i vite-plugin-svg-icons -D
此时安装一下依赖包 npm i fast-glob -D
在main.ts中引入 import 'virtual:svg-icons-register'
3.注册插件vite.config.ts
import { createSvgIconsPlugin } from "vite-plugin-svg-icons";
plugins: [
vue(),
createSvgIconsPlugin({
// 指定需要缓存的图标文件夹
iconDirs: [resolve(process.cwd(), "src/assets/svg")],
// 指定symbolId格式
symbolId: "icon-[dir]-[name]",
}),
],
4.封装组件 components/public/SvgIcon.vue 其中public下面的为公共组件,通过目录下的index.ts统一注册
<script setup lang="ts">
defineProps({
name: {
type: String,
required: true,
},
color: {
type: String,
default: "#333"
},
width: {
type: String,
default: "24px"
},
height: {
type: String,
default: "24px"
},
prefix: {
type: String,
default: '#icon-'
},
})
</script>
<template>
<svg :style="{ width, height }">
<use :href="prefix + name" :fill="color" />
</svg>
</template>
5.新建全局入口文件 components/public/index.ts
import { App, Component } from "vue";
import SvgIcon from "./SvgIcon/index.vue";
import "virtual:svg-icons-register";
const allComponents: {
[name: string]: Component;
} = {
SvgIcon,
};
const publicComponents = {
install(app: App): void {
Object.keys(allComponents).forEach((key) => {
app.component(key, allComponents[key]);
});
},
};
export default publicComponents;
6.在main.ts中注册
//导入所有公共组件
import publicComponents from "./components/public";
createApp(App).use(publicComponents).mount("#app");
7.使用