安裝#
npm install vite-plugin-svg-icons --save-dev
設定#
-
在
vite.config.ts
中進行設定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
中引入import "virtual:svg-icons-register";
-
定義組件
SvgIcon.vue
<template> <svg :class="svgClass" aria-hidden="true"> <use :xlink:href="iconName" :fill="props.color" /> </svg> </template> <script lang="ts" setup> 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"; }); </script> <style scope lang="scss"> .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; } </style>
-
在
main.ts
中註冊為全局組件import svgIcon from "./components/SvgIcon/index.vue"; app.component("svg-icon", svgIcon);
使用#
<template>
<div style="display: flex; gap: 20px">
<svg-icon iconClass="Github"></svg-icon>
<svg-icon iconClass="Aiming"></svg-icon>
</div>
</template>
<script setup lang="ts">
</script>
<style lang="scss" scoped>
</style>