zorroe

zorroe

Using the plugin vite-plugin-svg-icons in Vue 3.

Installation#

npm install vite-plugin-svg-icons --save-dev

Configuration#

  1. Configure in vite.config.ts

    import { defineConfig } from "vite";
    import { createSvgIconsPlugin } from "vite-plugin-svg-icons";
    import vue from "@vitejs/plugin-vue";
    import path from "path";
    
    // https://vitejs.dev/config/
    export default defineConfig({
      plugins: [
        vue(),
        createSvgIconsPlugin({
          iconDirs: [path.resolve(process.cwd(), "src/assets/icons/svg")],
          symbolId: "icon-[dir]-[name]",
        }),
      ],
    });
    
  2. Create the icons/svg directory in the src/assets directory of the project and place the SVG icon files in itimage-20230711195608293

  3. Import in main.ts

    import "virtual:svg-icons-register";
    
  4. Define the SvgIcon.vue component

    <template>
      <svg :class="svgClass" aria-hidden="true">
        <use :xlink:href="iconName" :fill="props.color" />
      </svg>
    </template>
    
    <script lang="ts" setup>
    import { computed } from "vue";
    
    const props = defineProps({
      iconClass: {
        type: String,
        required: true,
      },
      className: {
        type: String,
        default: "",
      },
      color: {
        type: String,
        default: "",
      },
    });
    
    const iconName = computed(() => `#icon-${props.iconClass}`);
    const svgClass = computed(() => {
      if (props.className) {
        return `svg-icon ${props.className}`;
      }
      return "svg-icon";
    });
    </script>
    
    <style scope lang="scss">
    .sub-el-icon,
    .nav-icon {
      display: inline-block;
      font-size: 15px;
      margin-right: 12px;
      position: relative;
    }
    
    .svg-icon {
      width: 1em;
      height: 1em;
      position: relative;
      fill: currentColor;
      vertical-align: -2px;
    }
    </style>
    
  5. Register as a global component in main.ts

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

Usage#

<template>
  <div style="display: flex; gap: 20px">
    <svg-icon iconClass="Github"></svg-icon>
    <svg-icon iconClass="Aiming"></svg-icon>
  </div>
</template>

<script setup lang="ts">

</script>

<style lang="scss" scoped>

</style>

Result#

image-20230711200625128

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.