安装
pnpm install vite-plugin-svg-icons -D
使用
- vite.config.ts配置
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
export default defineConfig({
plugins: [
···
···
createSvgIconsPlugin({
// 指定需要缓存的图标文件夹
iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],
// 指定symbolId格式
symbolId: 'icon-[dir]-[name]'
})
···
···
]
})
- 在 src/main.ts 内引入注册脚本
import 'virtual:svg-icons-register'
封装组件
- /src/components/SvgIcon.vue
<template>
<svg aria-hidden="true">
<use :xlink:href="symbolId" :fill="props.color"/>
</svg>
</template>
<script setup lang="ts">
interface Props {
prefix?: string
name: string
color?: string
}
const props = withDefaults(defineProps<Props>(), {
prefix: 'icon',
color: '#333'
})
const symbolId = computed(() => `#${props.prefix}-${props.name}`)
</script>
在 .vue 文件中使用
<template>
<SvgIcon name="icon1"/> // icon1.svg
<SvgIcon name="icon2"/> // icon2.svg
<SvgIcon name="dir-icon1"/> // dir/icon1.svg
</template>
<script setup lang='ts'>
import SvgIcon from '@/components/SvgIcon/SvgIcon.vue'
</script>
Typescript 支持
- tsconfig.json
{
"compilerOptions": {
"types": ["vite-plugin-svg-icons/client"]
}
}
如启动报错---Cannot find module 'fast-glob',安装 fast-glob
- pnpm add fast-glob