svg精灵图特征:
- 预加载:在项目运行时就生成所有图标只需要操作一次dom
- 高性能:内置缓存,仅当文件被修改时才会重新生成
打包svg地图
- 实现:根据 icons 文件svg图片打包到项目中,通过组件使用图标
1.安装插件
yarn add vite-plugin-svg-icons -D
# or
npm i vite-plugin-svg-icons -D
# or
pnpm install vite-plugin-svg-icons -D
2.使用插件,在vite.config.ts文件中配置
//引入
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import path from 'path'
//在plugins:[]中配置
// 生成svg精灵图插件
createSvgIconsPlugin({
// 指定图标文件夹,绝对路径(NODE代码)
iconDirs: [path.resolve(process.cwd(), 'src/icons')]
})
3.导入到main
import 'virtual:svg-icons-register'
4.组件中使用svg精灵图
<svg aria-hidden="true">
<!-- #icon-文件夹名称-图片名称 -->
<use href="#icon-[文件夹名]-[图片名]" />
</svg>
- 注:直接使用代码繁琐,可以封装svg精灵图组件
封装svg精灵图组件
1.在src组件中新建components/CpIcon.vue
封装svg精灵图:
<script setup lang="ts">
// 提供name属性即可
defineProps<{
name: string
}>()
</script>
<template>
<svg aria-hidden="true" class="cp-icon">
<use :href="`#icon-${name}`" />
</svg>
</template>
<style lang="scss" scoped>
.cp-icon {
// 和字体一样大
width: 1em;
height: 1em;
}
</style>
2.添加类型:在src目录新建文件types/components.d.ts
// 导入svg精灵图
import CpIcon from '@/components/CpIcon.vue'
// 声明 vue 类型模块
declare module 'vue' {
// 给 vue 添加全局组件类型,interface 和之前的合并
interface GlobalComponents {
// 定义具体组件类型,typeof 获取到组件实例类型
// typeof 作用是得到对应的TS类型
CpIcon: typeof CpIcon
}
}
3.组件中使用
<cp-icon name="[文件夹名]-[文件名]"></cp-icon>
本文介绍了如何在Vite项目中使用vite-plugin-svg-icons插件来预加载SVG图标,实现高性能并进行文件缓存。步骤包括安装插件、配置文件、创建封装的CpIcon.vue组件以及在组件中使用SVG精灵图。
416





