在Vite构建的项目中使用svg图标

1,025 阅读1分钟

在Vite构建的项目中使用svg图标

安装插件

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

文件配置

在vite.config.ts中进行文件配置

  • 首先引入插件
  • 其次在plugins中添加配置

iconDirs 中存放的就是图标文件地址数组,这里的目录是 src/assets/icons

// 引入svg需要用到的插件
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'

export default defineConfig({
    plugins:[
        vue(),
        // 配置svg图标
        createSvgIconsPlugin({
            // 指定需要缓存的图标文件夹
            iconDirs: [path.resolve(provess.cwd(), 'src/assets/icons')],
            // 指定symbolId格式
            symbolId: 'icon-[name]'/** 
            * 自定义插入位置 
            * @default: body-last 
            */ 
            inject?: 'body-last' | 'body-first'
            /** 
            * custom dom id 
            * @default: __svg__icons__dom__ 
            */ 
            customDomId: '__svg__icons__dom__',
            svgoOptions: {
                plugins: [
                  {
                      // 清除svg部分属性
                      name: 'removeAttrs',
                      params: { attrs: ['fill', 'stroke'] }
                  }
                ]
             }
        })
    ]
})

页面中使用

src/main.ts内引入注册脚本

import 'virtual:svg-icons-register'

vue方式

use标签中添加xlink:href属性,值为#icon-[svg文件名称],这里的值与配置文件中的icon-[name]匹配

<template>
  <svg aria-hidden="true">
    <use :xlink:href="symbolId" :fill="color" />
  </svg>
</template>

<script>
import { defineComponent, computed } from 'vue'

export default defineComponent({
  name: 'SvgIcon',
  props: {
    prefix: {
      type: String,
      default: 'icon',
    },
    name: {
      type: String,
      required: true,
    },
    color: {
      type: String,
      default: '#333',
    },
  },
  setup(props) {
    const symbolId = computed(() => `#${props.prefix}-${props.name}`)
    return { symbolId }
  },
})
</script>

react方式

export default function SvgIcon({
  name,
  prefix = 'icon',
  color = '#333',
  ...props
}) {
  const symbolId = `#${prefix}-${name}`

  return (
    <svg {...props} aria-hidden="true">
      <use href={symbolId} fill={color} />
    </svg>
  )
}

获取所有 symbolId

import ids from 'virtual:svg-icons-names'

配置说明

参数类型默认值说明
iconDirsstring[]-需要生成雪碧图的图标文件夹
symbolIdstringicon-[dir]-[name]svg 的 symbolId 格式,见下方说明
svgoOptionsboolean|SvgoOptionstruesvg 压缩配置,可以是对象Options
injectstringbody-lastsvgDom 默认插入的位置,可选body-first
customDomIdstring__svg__icons__dom__svgDom 插入节点的 ID