1. 安装vite-plugin-svg-icons插件
$ yarn add vite-plugin-svg-icons -D
# or
$ npm install vite-plugin-svg-icons -D
2. 插件配置
- 配置插件在vite.config.ts
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import path from 'path'
export default () => {
return {
plugins: [
createSvgIconsPlugin({
// 指定要缓存的图标文件夹<**必须和你存放svg文件夹路径一致**>
iconDirs: [path.resolve(process.cwd(), 'src/icons')],
// 指定symbolId格式<可以保持默认格式>
symbolId: 'icon-[dir]-[name]',
/**
* 自定义插入位置<选填>
* @default: body-last
*/
// inject?: 'body-last' | 'body-first'
/**
* 自定义dom id <可以保持默认格式>
* @default: __svg__icons__dom__
*/
customDomId: '__svg__icons__dom__',
}),
],
}
}
- 注册脚本在/src/main.ts添加
// /src/main.ts
import 'virtual:svg-icons-register'
这里已经生成了svg精灵图
3.组件中使用
- 创建组件
// /src/utils/validate.ts
/**
* 判断是否为外部资源
* @param { string } path
* @returns
*/
export function isExternal(path: string): boolean {
return /^(https?:|mailto:|tel:)/.test(path)
}
// /src/components/SvgIcon.vue
<template>
<!-- 展示外部图片 -->
<div
v-if="isExternal"
:style="styleExternalIcon"
class="svg-external-icon svg-icon"
:class="className"
></div>
<!-- 展示内部图片 -->
<svg v-else class="svg-icon" :class="className" aria-hidden="true">
<use :xlink:href="iconName" />
</svg>
</template>
<script lang="ts" setup>
import { isExternal as external } from '@/utils/validate'
import { computed } from 'vue'
const props = defineProps({
icon: {
type: String,
required: true
},
className: {
type: String,
default: ''
}
})
/**
* 判断当前图标是否为外部图标
*/
const isExternal = computed(() => external(props.icon))
/**
* 外部图标样式
*/
const styleExternalIcon = computed(() => ({
mask: `url(${props.icon}) no-repeat 50% 50%`,
'-webkit-mask': `url(${props.icon}) no-repeat 50% 50%`
}))
/**
* 内部图标
*/
const iconName = computed(() => `#icon-${props.icon}`)
</script>
<style scoped>
.svg-icon {
width: 1em;
height: 1em;
vertical-align: -0.15em;
fill: currentColor;
overflow: hidden;
}
.svg-external-icon {
background-color: currentColor;
mask-size: cover !important;
display: inline-block;
}
</style>
2.目录结构
# src/icons
- icon1.svg
- icon2.svg
- icon3.svg
- dir/icon1.svg
- 页面使用
<script setup lang="ts">
import SvgIcon from '@/components/SvgIcon.vue'
</script>
<template>
<SvgIcon icon="icon1"></SvgIcon>
<SvgIcon icon="icon2"></SvgIcon>
<SvgIcon icon="icon3"></SvgIcon>
<SvgIcon icon="https://xxx.xx.com/icon.svg"></SvgIcon>
<SvgIcon icon="dir-icon1"></SvgIcon>
</template>