通过 vite-plugin-svg-icons 插件整合 Iconfont
第三方图标库实现本地图标
参考: vite-plugin-svg-icons 安装文档
# 1. 安装依赖
| npm install -D fast-glob@3.2.11 |
| npm install -D vite-plugin-svg-icons@2.0.1 |
# 2. 创建 src/assets/icons
目录
放入从 Iconfont 复制的 svg
图标
# 3. main.ts
引入注册脚本
| |
| import 'virtual:svg-icons-register'; |
# 4. vite.config.ts
配置插件
| |
| import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'; |
| |
| export default ({command, mode}: ConfigEnv): UserConfig => { |
| return ( |
| { |
| plugins: [ |
| createSvgIconsPlugin({ |
| |
| iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')], |
| |
| symbolId: 'icon-[dir]-[name]', |
| }) |
| ] |
| } |
| ) |
| } |
# 5.SVG 组件封装
| <!-- src/components/SvgIcon/index.vue --> |
| <script setup lang="ts"> |
| const props = defineProps({ |
| prefix: { |
| type: String, |
| default: "icon", |
| }, |
| iconClass: { |
| type: String, |
| required: false, |
| }, |
| color: { |
| type: String, |
| }, |
| size: { |
| type: String, |
| default: "1em", |
| }, |
| }); |
| |
| const symbolId = computed(() => `#${props.prefix}-${props.iconClass}`); |
| </script> |
| |
| <template> |
| <svg |
| aria-hidden="true" |
| class="svg-icon" |
| :style="'width:' + size + ';height:' + size" |
| > |
| <use :xlink:href="symbolId" :fill="color" /> |
| </svg> |
| </template> |
| |
| <style scoped> |
| .svg-icon { |
| display: inline-block; |
| outline: none; |
| width: 1em; |
| height: 1em; |
| vertical-align: -0.15em; |
| fill: currentColor; |
| overflow: hidden; |
| } |
| </style> |
# 6. 组件使用
| |
| <template> |
| <el-button type="info"><svg-icon icon-class="block"/>SVG 本地图标</el-button> |
| </template> |