How to use svg icon in vite configuration vue3

Svg images are widely used in projects, how to use svg icons in vue3 + vite.

vite-plugin-svg-icons

  • Preload All icons are generated when the project is running, and only one dom operation is required
  • High performance Built-in cache, only regenerated when the file is modified
yarn add vite-plugin-svg-icons -D
# or
npm i vite-plugin-svg-icons -D
# or
pnpm install vite-plugin-svg-icons -D

Configure the plugin in vite.config.ts

import

import {createSvgIconsPlugin } from 'vite-plugin-svg-icons';

Then configure it in plugins

 plugins: [vue(),createSvgIconsPlugin({
      // 指定需要缓存的图标文件夹
    iconDirs: [path.resolve(process.cwd(), 'src/assets/svg')],
      // 指定symbolId格式
      symbolId: 'icon-[dir]-[name]',
    }),],

Then introduce it in main.ts

import 'virtual:svg-icons-register'

In svgIcon.vue

<template>
    <svg aria-hidden="true" class="svg-icon" :width="props.size" :height="props.size">
      <use :xlink:href="symbolId" rel="external nofollow"  :fill="props.color" />
    </svg>
  </template>
  
  <script setup lang="ts">
  import { computed } from 'vue'
  const props = defineProps({
    prefix: {
      type: String,
      default: 'icon'
    },
    name: {
      type: String,
      required: true
    },
    color: {
      type: String,
      default: '#333'
    },
    size: {
      type: String,
      default: '1em'
    }
  })
  const symbolId = computed(() => `#${props.prefix}-${props.name}`)
  </script>

Register globally in main.ts

import svgIcon from "@/components/SvgIcon/index.vue";
app.component('svg-icon', svgIcon)

 used in the page

<template>
    <svg-icon v-if="props.icon" :name="props.icon" />
    <span v-if="props.title" slot='title'>{
   
   { props.title }}</span>
</template>

<script setup lang="ts">
const props = defineProps({
    icon: {
        type: String,
        default: ''
    },
    title: {
        type: String,
        default: ''
    }
})
</script>

Guess you like

Origin blog.csdn.net/qq_27449993/article/details/127221528
Recommended