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 @ 2024-01-30 14:27  //唉  阅读(1333)  评论(0)    收藏  举报