How to use svg icons in the vue3 project built by vite?

1. Install the plugin: vite-plugin-svg-icons 

// 通过命令安装2个插件
npm i vite-plugin-svg-icons -D
npm i fast-glob -D

 as the picture shows

//package.json
 "devDependencies": {
    "@types/node": "^18.7.13",
    "@vitejs/plugin-vue": "^3.0.3",
    "fast-glob": "^3.2.12",
    "sass": "^1.54.5",
    "typescript": "^4.6.4",
    "vite": "^3.0.7",
    "vite-plugin-svg-icons": "^2.0.1",
    "vue-tsc": "^0.39.5"
  }

2. Configure the plug-in: configure createSvgIconsPlugin in vite.config.ts 

//vite.config.ts
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { join, resolve } from "path";
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'


// https://vitejs.dev/config/
export default defineConfig({
  base: "./",
  plugins: [
    vue(),
    createSvgIconsPlugin({
      iconDirs: [resolve(process.cwd(), 'src/assets/svg')],
      symbolId: 'icon-[dir]-[name]',
    }),
    
  ],
  resolve: {
    alias: {
      '@': join(__dirname, 'src'),
    }
  },
})

 Storage file path: src/assets/svg

- icon1.svg
- icon2.svg
- icon3.svg
- dir/icon1.svg

Then introduce the following code in main.ts:

//main.ts
import 'virtual:svg-icons-register'

 3. Packaged into components: SvgIcon.vue

<template>
    <svg aria-hidden="true" :style="{ width: size + 'px', height: size + 'px' }">
        <use :xlink:href="symbolId" :fill="color" />
    </svg>
</template>
<script setup lang="ts">
import { computed } from 'vue';

const props = defineProps({
    iconName: {
        type: String,
        required: true
    },
    color: {
        type: String,
        default: ''
    },
    size: {
        type: [Number, String],
        default: 18
    }
})
const symbolId = computed(() => `#icon-${props.iconName}`);

</script>


<style scoped>
.svg-icon {
    fill: currentColor;
    vertical-align: middle;
}
</style>

 4. How to use:

<template>
        <SvgIcon icon-name="icon1" ></SvgIcon>
</template>

<script setup lang="ts">
import SvgIcon from "@/components/SvgIcon.vue";
</script>

<style scoped lang="scss">
</style>

Reprinted to: How to use svg icons in the vue3 project built by vite? - Jianshu (jianshu.com) 

Guess you like

Origin blog.csdn.net/deng_zhihao692817/article/details/131845803