vue3中使用插件vite-plugin-svg-icons

安装

Copy
npm install vite-plugin-svg-icons --save-dev

配置

在vite.config.ts中进行配置

Copy
import { defineConfig } from "vite";
import { createSvgIconsPlugin } from "vite-plugin-svg-icons";
import vue from "@vitejs/plugin-vue";
import path from "path";

// https://vitejs.dev/config/
export default defineConfig({
plugins: [
vue(),
createSvgIconsPlugin({
iconDirs: [path.resolve(process.cwd(), "src/assets/icons/svg")],
symbolId: "icon-[dir]-[name]",
}),
],
});

在项目的src/assets目录下创建icons/svg目录并放入 svg 图标文件

在main.ts中引入

Copy
import "virtual:svg-icons-register";

定义组件SvgIcon.vue

Copy


<use :xlink:href="iconName" :fill="props.color" />




import { computed } from "vue";

const props = defineProps({
iconClass: {
type: String,
required: true,
},
className: {
type: String,
default: "",
},
color: {
type: String,
default: "",
},
});

const iconName = computed(() => `#icon-${props.iconClass}`);
const svgClass = computed(() => {
if (props.className) {
return `svg-icon ${props.className}`;
}
return "svg-icon";
});



.sub-el-icon,
.nav-icon {
display: inline-block;
font-size: 15px;
margin-right: 12px;
position: relative;
}

.svg-icon {
width: 1em;
height: 1em;
position: relative;
fill: currentColor;
vertical-align: -2px;
}


在main.ts中注册为全局组件

Copy
import svgIcon from "./components/SvgIcon/index.vue";

app.component("svg-icon", svgIcon);

使用

Copy


<svg-icon iconClass="Github"></svg-icon>
<svg-icon iconClass="Aiming"></svg-icon>











效果