安裝
我們可以使用以下命令來安裝 vite-plugin-svg-icons 插件:
npm install vite-plugin-svg-icons --save-dev
配置
在安裝了 vite-plugin-svg-icons 插件后,我們可以在 vite.config.js 中進行配置。以下是一個示例配置:
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 函數創建了一個插件。該插件接受一個配置對象,其中包含以下三個選項:
iconDirs:指定要處理的 SVG 文件夾路徑。
svgsDir:指定要生成的組件名稱。
symbolId:指定要生成的組件類型。
接下來我們需要在main.js中引入
import 'virtual:svg-icons-register'
使用
新建一個svg-icon組件,按照自己喜歡的方式全局引入或局部引入,內容如下:
<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>
如果遇到設置了顏色不生效,或者部分生效的問題,可以使用編輯器打開svg文件,看下標簽上的fill字段,設置為currentColor。
報錯
報錯:Cannot find package ‘fast-glob‘,安裝下對應依賴就可以了
npm install fast-glob -D