vue3+vite导入svg使用及相关配置

256 阅读1分钟

安装库:npm i vite-plugin-svg-icons fast-glob -D

  1. vite.config.js 文件
import { fileURLToPath, URL } from 'node:url'

// *******主要代码-插件引入*******
import { createSvgIconsPlugin } from "vite-plugin-svg-icons";

import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'

import path from "path";

export default defineConfig(({ command, mode }) => {
  const env = loadEnv(mode, process.cwd(), '')
  return {
    transpileDependencies: true,
    plugins: [
      vue(),
      // *******主要代码-插件配置*******
      createSvgIconsPlugin({
        // 指定需要缓存的图标文件夹
        iconDirs: [path.resolve(process.cwd(), 'src/icons')],
        // 指定symbolId格式
        symbolId: 'icon-[dir]-[name]',
      })
    ],
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url))
      }
    },
    server: {
      proxy: {
        [env.VITE_APP_BASE_API]: {
          target: env.VITE_APP_BASE_URL,
          secure: true,
          changeOrigin: true,
        }
      }
    },
    define: { 'process.env': {} }
  }
})

  1. main.js 文件

引入文件 import 'virtual:svg-icons-register'

  1. 创建 icons 文件夹

在 assets 文件夹中创建 icons 文件夹存放 svg

image.png

  1. 创建 svg 公共组件

在 components 文件夹中创建 svg 公共组件

image.png

代码如下

<template>
    <svg aria-hidden="true" :style="{ width: width + 'px', height: height + 'px' }">
        <use :xlink:href="symbolId" :fill="color" />
    </svg>
</template>

<script setup>
import { computed } from 'vue';
const props = defineProps({
    prefix: {
        type: String,
        default: 'icon',
    },
    name: {
        type: String,
        required: true,
    },
    color: {
        type: String,
        default: '#333',
    },
    width: {
        type: [Number, String],
        default: '24',
    },
    height: {
        type: [Number, String],
        default: '24',
    },
})
const symbolId = computed(() => `#${props.prefix}-${props.name}`);
</script>
  1. 使用 svg 组件
// 引入组件
import svgIcon from "@/components/svg/index.vue"

模板中使用
<svgIcon name="copy" />

Tip:如果项目很多地方都用到组件,可以在main.js中导入全局使用

import SvgIcon from "./icons/SvgIcon.vue";

const app = createApp(App)
app.component("Svg-icon",SvgIcon)