1. 安裝依賴插件 vite-plugin-svg-icons
vite-plugin-svg-icons 用於生成 svg 雪碧圖。
特點:
1.預加載 在項目運行時就生成所有圖標,只需操作一次 dom
2.高性能 內置緩存,僅當文件被修改時纔會重新生成
pnpm add vite-plugin-svg-icons
2. 安裝 fast-glob
該軟件包提供了遍歷文件系統的方法,並根據Unix Bash shell使用的規則返回與一組定義的指定模式匹配的路徑名,並進行了一些簡化,同時以任意順序返回結果。快速、簡單、有效。
pnpm add fast-glob
3. 配置 vite.config.ts
import { defineConfig } from 'vite'
import path from "path";
import {createSvgIconsPlugin} from 'vite-plugin-svg-icons'; // vite-plugin-svg-icons 用於自動導入 svg 圖標
export default defineConfig({
plugins: [
createSvgIconsPlugin({
// 需要自動導入的 svg 文件目錄(可自行修改)
iconDirs: [path.resolve(process.cwd(), "src/assets/icons")],
// 執行icon name的格式(可自行修改)
symbolId: "icon-[dir]-[name]",
// 更多配置請參考:https://github.com/vbenjs/vite-plugin-svg-icons/blob/HEAD/README.zh_CN.md
}),
]
});
4. 在 main.ts 入口註冊腳本
import "virtual:svg-icons-register"; // vite-plugin-svg-icons 插件註冊,不引入會導致svg圖標無法正常顯示
5. 封裝 SvgIcon 組件
可根據自己實際項目需要自行修改組件邏輯
<template>
<svg :style="iconStyle" aria-hidden="true">
<use :xlink:href="symbolId" />
</svg>
</template>
<script setup lang="ts" name="SvgIcon">
import { computed, CSSProperties } from "vue";
interface SvgProps {
name: string; // 圖標的名稱(Svg 文件名) ==> 必傳
prefix?: string; // 圖標的前綴 ==> 非必傳(默認爲"icon")
iconStyle?: CSSProperties; // 圖標的樣式 ==> 非必傳
}
// 接收父組件參數並設置默認值
const props = withDefaults(defineProps<SvgProps>(), {
prefix: "icon",
iconStyle: () => ({ width: "50px", height: "50px" }),
});
const symbolId = computed(() => `#${props.prefix}-${props.name}`);
</script>
6. 引入組件使用
// 導入
import SvgIcon from '@/components/SvgIcon/index.vue';
// 使用
<SvgIcon :name="item.name" :iconStyle="{ width: '24px', height: '24px' }" />
參考文章
vite-plugin-svg-icons 官方文檔
fast-glob NPM 文檔
Vite2 + Vue3添加svg的使用並通過svg實現自定義Icon組件