使用vite-plugin-svg-icons 插件
1.安装
pnpm add vite-plugin-svg-icons -D
2.vite.config.ts 配置
import {fileURLToPath, URL} from 'node:url'
import {createSvgIconsPlugin} from "vite-plugin-svg-icons"
// plugins下新增插件
createSvgIconsPlugin({
iconDirs: [fileURLToPath(new URL('./src/assets/icons', import.meta.url))],
symbolId:"icon-[name]"
})
3.main.ts 引入
import "virtual:svg-icons-register"
4.新增组件SvgIcon,在components文件下新增SvgIcon组件
<template>
<svg :class="svgClass" aria-hidden="true">
<use :xlink:href="iconName" :color="color"></use>
</svg>
</template>
<script setup lang="ts">
import {computed} from "vue";
const props = defineProps({
name: {
type: String,
required: true
},
className: {
type: String,
default: ''
},
color:{
type:String,
default:'',
}
})
const iconName = computed(() => `#icon-${props.name}`)
const svgClass = computed(() => { return props.className ? 'svg-icon ' + props.className : 'svg-icon'})
</script>
<style scoped>
.svg-icon {
width: 1em;
height: 1em;
vertical-align: -0.15em;
fill: currentColor;
overflow: hidden;
}
</style>
ok,配置成功,启动~
【坑】:Cannot find package ‘fast-glob‘ 安装后启动报错缺少 fast-glob插件
发现vite-plugin-svg-icons配置后重启缺少fast-glob依赖,安装:
pnpm install fast-glob -D
ok,安装完大功告成!