記錄插件vite-plugin-svg-icons的安裝與使用

安裝

我們可以使用以下命令來安裝 vite-plugin-svg-icons 插件:

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

配置

在安裝了 vite-plugin-svg-icons 插件后,我們可以在 vite.config.js 中進(jìn)行配置。以下是一個(gè)示例配置:

import { defineConfig } from 'vite'
import svgIcons from 'vite-plugin-svg-icons'

export default defineConfig({
  plugins: [
    svgIcons({
      // 指定要處理的 SVG 文件夾路徑
      iconDirs: [require.resolve('src/assets/svgs')],
      // 指定要生成的組件名稱
      svgsDir: 'src/svgs',
      // 指定要生成的組件類型
      symbolId: 'icon-[dir]-[name]',
    }),
  ],
})

在上面的配置中,我們使用 svgIcons 函數(shù)創(chuàng)建了一個(gè)插件。該插件接受一個(gè)配置對象,其中包含以下三個(gè)選項(xiàng):

iconDirs:指定要處理的 SVG 文件夾路徑。
svgsDir:指定要生成的組件名稱。
symbolId:指定要生成的組件類型。

接下來我們需要在main.js中引入

import 'virtual:svg-icons-register'

使用

新建一個(gè)svg-icon組件,按照自己喜歡的方式全局引入或局部引入,內(nèi)容如下:

<template>
    <svg class="svg-icon" aria-hidden="true" v-on="$listeners">
        <use :href="symbolId" :fill="color" />
    </svg>
</template>

<script>
export default {
    name: 'SvgIcon',
    props: {
        prefix: {
            type: String,
            default: 'icon',
        },
        name: {
            type: String,
            required: true,
        },
        color: {
            type: String,
            default: '#333',
        },
    },
    data() {
        return {
            symbolId: ''
        }
    },
    mounted() {
        this.symbolId = `#${this.prefix}-${this.name}`
    },
}
</script>

<style scoped>
.svg-icon {
    width: 1em;
    height: 1em;
    fill: currentColor;
    overflow: hidden;
}
</style>

頁面中使用:

<svg-icon name="content-msg"></svg-icon>

如果遇到設(shè)置了顏色不生效,或者部分生效的問題,可以使用編輯器打開svg文件,看下標(biāo)簽上的fill字段,設(shè)置為currentColor。

報(bào)錯(cuò)

報(bào)錯(cuò):Cannot find package ‘fast-glob‘,安裝下對應(yīng)依賴就可以了

npm install fast-glob -D
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容