vue3+ts+vite项目中使用vite-plugin-svg-icons插件处理svg

1.安装依赖:npm install vite-plugin-svg-icons -D

2.vite.config.ts 中配置:

复制代码
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'

// 在export default ({ command, mode }: ConfigEnv): UserConfig中的plugins数组中添加代码
plugins: [
      createSvgIconsPlugin({
        // 指定需要缓存的图标文件夹,地址可改
        iconDirs: [path.resolve(process.cwd(), 'src/assets/svg')],
        // 指定symbolId格式
        symbolId: 'icon-[dir]-[name]',
      })
],
复制代码

 3.main.ts中添加代码:

import 'virtual:svg-icons-register'
4.在components创建SvgIcon.vue组件
复制代码
<script lang="ts" setup>
defineProps({
  name: {
    type: String,
    required: true,
    default: 'car',
  },
  size: {
    type: Number,
    default: 30,
  },
  color: {
    type: String,
    default: '#000',
  },
})
</script>

<template>
  <svg class="svg-icon" :style="{ width: `${size}px`, height: `${size}px`, color: `${color}` }">
    <use :xlink:href="`#icon-${name}`" :fill="color" />
  </svg>
</template>
复制代码

5.在main.ts中全局引用

import svgIcon from './components/SvgIcon.vue'

const app = createApp(App)
app.component('SvgIcon', svgIcon)

6.在src/assets文件价下新建svg文件夹,将下载的svg文件放在这个文件夹下

7.在组件中使用

<svg-icon name="airService" :size="16" />

 

posted @   //唉  阅读(948)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示