1.安装
cnpm i vite-plugin-svg-icons -D
2.配置 vite.config.ts
import viteSvgIcons from 'vite-plugin-svg-icons'; import path from 'path'; export default () => { return { plugins: [ viteSvgIcons({ // 指定需要缓存的图标文件夹 iconDirs: [path.resolve(process.cwd(), 'src/icons')], // 指定symbolId格式 symbolId: 'icon-[dir]-[name]', }), ], }; };
3.在 src/main.ts 内引入注册脚本
import 'virtual:svg-icons-register';
4.创建组件
//src/components/SvgIcon/index.vue <template> <svg aria-hidden="true" class="svg-icon-spin"> <use :xlink:href="symbolId" :fill="color" /> </svg> </template> <script lang="ts"> import { defineComponent, computed } from 'vue' export default defineComponent({ name: 'SvgIcon', props: { prefix: { type: String, default: 'icon' }, name: { type: String, required: true }, color: { type: String, default: '#333' } }, setup(props) { const symbolId = computed(() => `#${props.prefix}-${props.name}`) return { symbolId } } }) </script> <style lang="less" scoped> .svg-icon-spin { width: 1em; height: 1em; fill: currentColor; vertical-align: middle; } </style>
5.icons 目录结构
src/icons
- icon1.svg - icon2.svg - icon3.svg - dir/icon1.svg
6.使用
<template> <div> <SvgIcon name="icon1"></SvgIcon> <SvgIcon name="icon2"></SvgIcon> <SvgIcon name="icon3"></SvgIcon> <SvgIcon name="dir-icon1"></SvgIcon> </div> </template> <script> import { defineComponent, computed } from 'vue'; import SvgIcon from './components/SvgIcon.vue'; export default defineComponent({ name: 'App', components: { SvgIcon }, }); </script>