vite-plugin-svg-icons github地址

Feature

  • Preloading All icons are generated when the project is running, and you only need to operate dom once.
  • High performance Built-in cache, it will be regenerated only when the file is modified.

安装

环境要求

  • node version: >=12.0.0
  • vite version: >=2.0.0
npm i vite-plugin-svg-icons -D
# or
pnpm add -D vite-plugin-svg-icons

vite.config.js 配置

import { defineConfig, loadEnv } from 'vite'
import { resolve } from 'path'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'

// https://vitejs.dev/config/
export default defineConfig(({ mode, command }) => {
  return {
    plugins: [
      /* ... */
      createSvgIconsPlugin({
        // 指定需要缓存的图标文件夹
        iconDirs: [path.resolve(process.cwd(), 'src/assets/icons/svg')],
        // 指定symbolId格式
        symbolId: 'icon-[dir]-[name]'
      })
    ]
    resolve: {
      // https://cn.vitejs.dev/config/#resolve-alias
      alias: {
        '@': resolve(__dirname, 'src'),
      }
    },
    server: {
      host: '0.0.0.0',
      port: 9881
    },
  }
})

新建 SvgIcon 组件

  • src/components/SvgIcon/index.vue
<!-- vue文件 index.vue -->
<template>
  <svg :class="svgClass" aria-hidden="true">
    <use :xlink:href="iconName" :fill="color" />
  </svg>
</template>

<script setup>
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(() => props.className ? `svg-icon ${props.className}` : 'svg-icon')
</script>

<style lang="scss" scoped>
.svg-icon {
  width: 1em;
  height: 1em;
  position: relative;
  fill: currentColor;
}
</style>
  • src/components/SvgIcon/svgicon.js

UI组件库用的是 Antd Vue

// svgicon.js
import * as components from '@ant-design/icons-vue'

export default {
  install: (app) => {
    for (const key in components) {
      const componentConfig = components[key];
      app.component(componentConfig.name, componentConfig);
    }
  },
};

main.js 全局注册

  • 导入上面新建的两个文件
// main.js
// svg图标
import 'virtual:svg-icons-register'
import SvgIcon from '@/components/SvgIcon/index.vue'
import antdvueIcons from '@/components/SvgIcon/svgicon.js'
  • 全局注册
// main.js
import { createApp } from 'vue'

const app = createApp(App)
app.component('svg-icon', SvgIcon)

app.use(antdvueIcons)
  .mount('#app')

组件页面使用

<template>
	<svg-icon icon-class="meeting" style="width: 40px; height: 155px;" />
</template>

<script setup>
import { defineAsyncComponent } from 'vue'

const SvgIcon = defineAsyncComponent(() => import('@/components/SvgIcon/index.vue'))
</script>
Logo

欢迎加入 MCP 技术社区!与志同道合者携手前行,一同解锁 MCP 技术的无限可能!

更多推荐