全局注册svg批量自动引入,动态修改svg以及样式配置问题

1.安装依赖

npm i vite-plugin-svg-icons

2.文件存放svg

 

3.全局组件svg-icon(直接放到全局组件目录下)

<template>
  <svg class="svg-icon">
    <use :xlink:href="`#icon-${props.name}`" class="mySVG"
      :style="'stroke:' + props.color + ';color:' + props.color + ';fill:' + props.color"
        />
  </svg>
</template>

<script setup lang="ts">
type Props = {
  name: string,
  color?: string
}
const props = withDefaults(defineProps<Props>(), {
  name: '',
  color: ''
})

</script>

<style lang="scss" scoped>

//这里可以自定义一些样式,例如:
.svg-icon {
  display: inline-block;
  overflow: hidden;
  vertical-align: -0.15em;
  fill: currentColor;
  display: flex;
  width: 32px;
  height: 20px;
  // align-items: center;
  // justify-content: center;
}
</style>

4.vite配置:vite.config.ts

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

createSvgIconsPlugin({
      // 指定要扫描的图标文件夹
      iconDirs: [path.resolve(process.cwd(), 'src/assets/svg')],
      // 指定symbolId格式
      symbolId: 'icon-[dir]-[name]',
    }),
View Code

 

5.main.js 引入

import 'virtual:svg-icons-register'
 
// 注册全局SvgIcon组件===单独注册方式
app.component('SvgIcon',SvgIcon)
 
如果是全局组件已经注册 这里无需单独注册
 
6.组件使用

 

效果

 

7.fill样式无效

如果svg的内联样式设置fill,组件里就无法修改

需要修改svg代码里的fill:currentColor

 
 
8. 如何批量自动修改fill ?!

使用 vite-plugin-svgo 自动转换

npm install vite-plugin-svgo -D

 配置 vite.config.js

import { defineConfig } from 'vite'
import svgo from 'vite-plugin-svgo'

export default defineConfig({
  plugins: [
    svgo({
      multipass: true,
      plugins: [
        {
          name: 'preset-default',
          params: {
            overrides: {
              // 移除内联 fill 属性(若需强制覆盖)
              removeAttrs: { attrs: 'fill' }
            }
          }
        },
        // 直接转换 fill 值为 currentColor
        {
          name: 'convertColors',
          params: { currentColor: true }
        }
      ]
    })
  ]
})

待实践验证。。。

posted @ 2025-02-27 16:35  树叶铃铛  阅读(210)  评论(0)    收藏  举报