11.Vite项目如何全局封装 Svg 插件

书诚小驿2024/11/12前端知识库Vue3

一、使用 Svg 插件

  1. 安装 SVG 依赖插件
npm i vite-plugin-svg-icons -D
npm i fast-glob
  1. vite.config.ts 中配置插件
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import vueDevTools from "vite-plugin-vue-devtools";
import { createSvgIconsPlugin } from "vite-plugin-svg-icons";
import path from "path";
export default defineConfig({
  plugins: [
    vue(),
    vueDevTools(),
    createSvgIconsPlugin({
      iconDirs: [path.resolve(process.cwd(), "src/assets/icons")],
      symbolId: "icon-[dir]-[name]",
    }),
  ],
  resolve: {
    alias: {
      "@": path.resolve("./src"),
    },
  },
  server: {
    port: "8080",
  },
});
  1. main.js引入 svg 配置
import "virtual:svg-icons-register";

二、封装 svg 组件

  1. 新建component/Svgicon/index.vue
<template>
  <svg class="svg-icon" :class="className" aria-hidden="true">
    <use :xlink:href="iconName" />
  </svg>
</template>

<script setup>
import { defineProps, computed } from "vue";
const props = defineProps({
  // icon 图标
  icon: {
    type: String,
    required: true,
  },
  // 图标类名
  className: {
    type: String,
    default: "",
  },
});
const iconName = computed(() => `#icon-${props.icon}`);
</script>

<style scoped>
.svg-icon {
  width: 100%;
  height: 100%;
  fill: currentColor;
  overflow: hidden;
}
</style>
  1. 下载 Svg 存放在src/assets/icons目录下

  2. 引入 Svgicon 组件

<script setup>
import SvgIcon from "../components/SvgIcon/index.vue";
</script>

<template>
  <div class="wrapper">
    <svg-icon icon="logo" />
  </div>
</template>
<style lang="scss" scoped>
.wrapper {
  width: 100%;
  height: 100%;
}
.svg-container {
  vertical-align: middle;
  display: inline-block;
  width: 80px;
  height: 80px;
}
</style>
  1. 打开终端,执行npm run dev运行
npm run dev

9f5512443f6c8a9db1a4c3860c2527b.png

最后更新时间' 2025/1/3 14:16:58