Skip to content

使用图标管理工具

传统 SVG 使用痛点

  • 手动维护多个 SVG 文件
  • 重复编写 <svg></svg> 标签导致代码冗余
  • 无法按需加载造成资源浪费
  • 修改颜色/样式需要操作 DOM
  • 频繁的 HTTP 请求影响性能

安装

bash
npm i vite-plugin-svg-icons -D

配置

  1. 在vite.config.js中配置
    • 导入vite-plugin-icons
js
import { createSvgIconsPlugin } from "vite-plugin-svg-icons";
  • 在plugins中添加
js
plugins: [
  createSvgIconsPlugin({
    // 指定图标文件夹,绝对路径(NODE代码)
    iconDirs: [path.resolve(process.cwd(), "src/assets/icons")],
    // 指定symbolId格式
    symbolId: "icon-[dir]-[name]",
  }),
],
  1. 在main.js中导入

    js
    import "virtual:svg-icons-register";
  2. 在组件中使用

    vue
    <svg class="icon" aria-hidden="true">
      <use xlink:href="#icon-svg文件名"></use>
    </svg>

补充

  • 诺使用了ts,可能无法识别,需要在src/types/svg-icons.d.ts中配置
ts
/// <reference types="vite-plugin-svg-icons/client" />

declare module 'virtual:svg-icons-register' {
    const content: () => void;
    export default content;
}
  • 再在tsconfig.app.json中引入
json
{
  "include": [
    "src/types/*.d.ts"
  ]
}

使用

  • 在项目路径 src/assets中创建一个icons 的文件夹,用于存放 SVG 图标文件。
  • 在图标网站,如:iconfont复制svg代码
  • 创建一个SVG文件,如:example.svg,将复制的代码粘贴到文件中。

创建组件

vue
<template>
    <div>
        <svg :style="{ width: props.size + 'px', height: props.size + 'px' }">
            <use :xlink:href="fullName" :fill="props.color"></use>
        </svg>
    </div>
</template>

<script setup lang="ts">
import { computed } from 'vue';

const props = defineProps({
    prefix: {
        type: String,
        default: '#icon-',
    },
    icon: {
        type: String,
        default: 'eye',
    },
    size: {
        type: Number,
        default: 24,
    },
    color: {
        type: String,
        default: '#000',
    },
})

const fullName = computed(() => {
    return props.prefix + props.icon;
})
</script>

<style scoped></style>

这是我的个人文档