封装icon图标

102 阅读1分钟

tt-one.webp

安装插件

yarn add vite-plugin-svg-icons -D
# or
npm i vite-plugin-svg-icons -D
# or
pnpm install vite-plugin-svg-icons -D

使用插件

vite.config.ts

import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import path from 'path'

export default defineConfig({
  plugins: [
    vue(),
    //配置 icon 图标
    createSvgIconsPlugin({
      // 指定图标文件夹,绝对路径(NODE代码)
      iconDirs: [path.resolve(process.cwd(), 'src/icons')],
      // 指定图标访问的名称
      symbolId: 'icon-[dir]-[name]'
    })
  ],
  //配置@别名
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    }
  },
})

main.ts

// 自动引入svg图标
import 'virtual:svg-icons-register'

如何直接使用组件不需要引入和注册

安装

pnpm add unplugin-vue-components -D

vite-config-ts 配置

// 引入插件
import Components from 'unplugin-vue-components/vite'

export default defineConfig({
  plugins: [
    vue(),
    // 即可
    Components({})
})

如何让组件有类型声明

vite-config-ts 配置

export default defineConfig({
  plugins: [
    vue(),
    // 即可
    Components({
      // 类型声明文件
      dts: false, // 生成 .d.ts声明文件 components.d.ts  env.d.ts
    })
})

src/types/components.d.ts

import SvgIcon from '@/components/SvgIcon.vue'

declare module 'vue' {
  interface GlobalComponents {
    SvgIcon: typeof SvgIcon
  }
}

创建一个SvgIcon组件

src/components/SvgIcon.vue

<script setup lang='ts'>
defineProps<{
  name: string
  color?: string
}>()
</script>
  
<template>
  <svg aria-hidden="true" class="svgIcon">
    <use :href="`#icon-${name}`" :fill="color" />
  </svg>
</template>
  
<style scoped lang='scss'>
  .svgIcon{
    width: 1em;
    height: 1em;
    fill: currentcolor; /* 定义元素的颜色,currentColor是一个变量,这个变量的值就表示当前元素的color值,如果当前元素未设置color值,则从父元素继承 */
  }
</style>

创建icon 放置svg

src/icons/目录名/XXX.svg 放置svg的图片

image.png

使用

<SvgIcon name="myIcons-delete"></SvgIcon>