使用 vite-plugin-svg-icons 封装 svg组件

本文介绍了如何在Vue项目中安装并配置vite-plugin-svg-icons,管理SVG图标,以及在Vite中全局注册SvgIcon组件,同时提到了fast-glob插件的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

安装vite-plugin-svg-icons  @types/node

npm i vite-plugin-svg-icons --save
npm i  @types/node --save
or
yarn add vite-plugin-svg-icons
yarn add @types/node --save

配置 vite.config.ts 文件

import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import path from 'node:path'
plugins:[
vue(),
createSvgIconsPlugin({
 // 图标文件夹为src/assets/icons
    iconDirs: [path.resolve(process.cwd(), 'src/assets/icons/svg')],
   // 指定symbolId格式
    symbolId: 'icon-[dir]-[name]',
})
]

创建SvgIcon文件

<template>
  <svg aria-hidden="true" class="svg-icon" :class="svgClass" :width="width" :height="height">
    <!--  :fill="color"  -->
    <use :xlink:href="symbolId" :fill="color" />
  </svg>
</template>
<script setup lang="ts">
const props = defineProps({
  prefix: {
    type: String,
    default: 'icon',
  },
  name: {
    type: String,
    required: true,
  },
  color: {
    type: String,
    default: '#333',
  },
  width: {
    type: String,
    default: '16px',
  },
  height: {
    type: String,
    default: '16px',
  },
  className: {
    type: String,
    default: '',
  },
})

const symbolId = computed(() => `#${props.prefix}-${props.name}`)

const svgClass = () => {
  if (props.className) {
    return `svg-icon ${props.className}`
  } else {
    return 'svg-icon'
  }
}
</script>

<style scoped>

</style>

在main.ts中全局注册 SvgIcon

import 'virtual:svg-icons-register'
import SvgIcon from '@/components/svgIcon/index.vue'
app.component('SvgIcon', SvgIcon)
注意:如果出现了这个报错

安装 fast-glob 插件

npm i fast-glob --save
or
yarn add fast-glob --savw

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值