实现:将 icons 文件夹下的 svg 图标打包到项目中、生成 svg 雪碧图,通过组件使用图标。
步骤:
1. 安装 vite-plugin-svg-icons
npm i vite-plugin-svg-icons -D
2. vite.config.ts 中的配置插件
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import path from 'path'
export default defineConfig({
plugins: [
vue(),
createSvgIconsPlugin({
# 指定需要缓存的图标文件夹
iconDirs: [path.resolve(process.cwd(), 'src/icons')],
# 指定symbolId格式
symbolId: 'icon-[dir]-[name]'
})
]
})
3. 在 src/main.ts 内引入注册脚本
import 'virtual:svg-icons-register'
到这里 svg 雪碧图已经生成
4. 封装svg组件
src / components / 新建 cp-icon.vue 组件
<script setup lang="ts">
defineProps<{
name: string
}>()
</script>
<template>
<svg aria-hidden="true" class="cp-icon">
<!-- #icon-文件夹名称-图片名称 -->
<use :href="`#icon-${name}`" />
</svg>
</template>
<style lang="scss" scoped>
.cp-icon {
// 和字体一样大
width: 1em;
height: 1em;
}
</style>
5. 配置 cp-icon 组件类型声明
修改 src / types / components.d.ts 内容
import CpIcon from '@/components/cp-icon.vue'
declare module 'vue' {
interface GlobalComponents {
CpIcon: typeof CpIcon
}
}
6. App.vue 中使用
<cp-icon name="home-article-active" />
End---------------------------