安装vite-plugin-svg-icons @types/node
npm i vite-plugin-svg-icons --save
npm i @types/node --save
or
yarn add vite-plugin-svg-icons
yarn add @types/node --save
配置 vite.config.ts 文件
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import path from 'node:path'
plugins:[
vue(),
createSvgIconsPlugin({
// 图标文件夹为src/assets/icons
iconDirs: [path.resolve(process.cwd(), 'src/assets/icons/svg')],
// 指定symbolId格式
symbolId: 'icon-[dir]-[name]',
})
]
创建SvgIcon文件
<template>
<svg aria-hidden="true" class="svg-icon" :class="svgClass" :width="width" :height="height">
<!-- :fill="color" -->
<use :xlink:href="symbolId" :fill="color" />
</svg>
</template>
<script setup lang="ts">
const props = defineProps({
prefix: {
type: String,
default: 'icon',
},
name: {
type: String,
required: true,
},
color: {
type: String,
default: '#333',
},
width: {
type: String,
default: '16px',
},
height: {
type: String,
default: '16px',
},
className: {
type: String,
default: '',
},
})
const symbolId = computed(() => `#${props.prefix}-${props.name}`)
const svgClass = () => {
if (props.className) {
return `svg-icon ${props.className}`
} else {
return 'svg-icon'
}
}
</script>
<style scoped>
</style>
在main.ts中全局注册 SvgIcon
import 'virtual:svg-icons-register'
import SvgIcon from '@/components/svgIcon/index.vue'
app.component('SvgIcon', SvgIcon)
注意:如果出现了这个报错
安装 fast-glob 插件
npm i fast-glob --save
or
yarn add fast-glob --savw