# [Vite] Vite Plugin - vite-plugin-svg-icons ###### tags: `Vite` `SVG` ## 安裝 :::warning Node 版本 >= 12.0.0 Vite 版本 >= 2.0.0 ::: 以下方式任選一個 * `npm i vite-plugin-svg-icons -D` * `yarn add vite-plugin-svg-icons -D` * `pnpm install vite-plugin-svg-icons -D` ## Vite 專案配置 [官方文件](https://github.com/vbenjs/vite-plugin-svg-icons#usage) ## Nuxt 3 專案配置 1. Configuration ```typescript // nuxt.config.ts import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'; import path from 'path'; export default defineNuxtConfig({ vite: { plugins: [ createSvgIconsPlugin({ // 假設 .svg 圖檔都放在 assets/icons 資料夾內 iconDirs: [path.resolve(process.cwd(), 'assets/icons')], // symbolId 格式 symbolId: 'icon-[dir]-[name]', }), ], }, }); ``` 2. 在進入點的 component(App.vue 或 layouts/default.vue) 內 import ```javascript <script setup> import 'virtual:svg-icons-register'; </script> ``` 3. 創建 `SvgIcon` component ```htmlmixed <script setup> const props = defineProps({ prefix: { type: String, default: 'icon', }, name: { type: String, required: true, }, color: { type: String, default: '#333', }, }); const symbolId = computed(() => `#${props.prefix}-${props.name}`); </script> <template> <svg aria-hidden="true"> <use :href="symbolId" :fill="color" /> <!-- 文件中英範例不同,但兩種寫法結果一樣 --> <!-- <use :xlink:href="symbolId" :fill="color" /> --> </svg> </template> ``` 4. 使用 ```htmlmixed <!-- 顯示 assets/icons/icon-link.svg --> <SvgIcon class="icon" name="icon-link" color="#00f" /> <!-- 顯示 assets/icons/sns/icon-ig.svg --> <SvgIcon class="icon" name="sns-icon-ig" /> <SvgIcon class="icon" name="icon-ig" prefex="icon-sns" /> ``` ## 參考資料 * [vite-plugin-svg-icons](https://github.com/vbenjs/vite-plugin-svg-icons "GitHub - vbenjs/vite-plugin-svg-icons: Vite Plugin for fast creating SVG sprites.") --- :::info 建立日期:2023-08-18 更新日期:2023-08-22 :::