使用Vite插件 实现自定义SVG组件

插件: vite-plugin-svg-icons

官方文档
https://github.com/vbenjs/vite-plugin-svg-icons/blob/main/README.zh_CN.md

  • 安装
yarn add vite-plugin-svg-icons -D
# or
npm i vite-plugin-svg-icons -D
# or
pnpm install vite-plugin-svg-icons -D
  • VITE配置
// vite-plugin-svg-icons
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import path from 'path'

// https://vitejs.dev/config/
export default defineConfig({
  // ...
    plugins: [
       // svg 加载
        createSvgIconsPlugin({
            // 指定需要缓存的图标文件夹 根据实际配置 svg必须在文件夹下
            iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],
            // 指定symbolId格式
            symbolId: 'icon-[dir]-[name]',

            /**
             * 自定义插入位置
             * @default: body-last
             * @options body-last  | 'body-first'
             */
            inject: 'body-last',

            /**
             * custom dom id
             * @default: __svg__icons__dom__
             */
            customDomId: '__svg__icons__dom__'
        })
  ],
})
  • main.js / ts
在 src/main.ts 内引入注册脚本
// eslint-disable-next-line import/no-unresolved
import 'virtual:svg-icons-register'

// eslint 会报错 可在.eslintrc.cjs 中关闭  或者 建议上面单次注释
'import/no-unresolved': 'off',

此时已经完成了基础配置,如何在组件中使用呢?

假设这么个目录结构

src
   /assets
       /icons
         - name/other.svg
         - user.svg
         - pwd.svg
  • 基础使用
   <svg aria-hidden="true">
      <!-- #icon-文件夹名称-图片名称 -->
       <!--#icon必须 pwd是svg文件名  -->
      <use href="#icon-pwd" />  pwd.svg
      <use href="#icon-user" />  user.svg
      <use href="#icon-name-other" />  other.svg
    </svg>
  • 封装组件
<template>
  <svg aria-hidden="true" class="svg-icon">
    <use :xlink:href="symbolId" :fill="color" />
  </svg>
</template>

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

const props = defineProps<{
  name: string
  color?: string
 }>()
const symbolId = computed(() => `#icon-${props.name}`)
</script>
<style lang="less" scoped>
.svg-icon {
  width: 1em;
  height: 1em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}
</style>

  • 组件使用
<svgIcon name="pwd" :color="'#0000ff'" style="width: 20px; height: 20px; "></svgIcon>

import svgIcon from '@/components/SvgIcons/index.vue'

以上
– END –

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值