vue3中使用插件vite-plugin-svg-icons

2,516 阅读2分钟

在开发项目的时候经常会用到svg矢量图,而且我们使用SVG以后,页面上加载的不再是图片资源,

这对页面性能来说是个很大的提升,而且我们SVG文件比img要小的很多,放在项目中几乎不占用资源。

安装SVG依赖插件

pnpm install vite-plugin-svg-icons -D

vite.config.ts中配置插件

import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import path from 'path'
export default () => {
  return {
    plugins: [
      createSvgIconsPlugin({
        // 指定 SVG图标 保存的文件夹路径
        iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],
        // 指定 使用svg图标的格式
        symbolId: 'icon-[dir]-[name]',
      }),
    ],
  }
}

在项目的src/assets目录下新建一个目录 icons,保存所有的svg图标文件

入口文件main.ts导入

import 'virtual:svg-icons-register'

基本使用

<!-- svg:图标外层容器节点,内部需要与use标签结合使用 -->
<svg style="width: 600px; height:600px">
    <!-- 'xlink:href执行用哪一个图标,属性值务必icon-图标名字·' -->
    <!-- use标签fi11属性可以设置图标的颜色 -->
    <use xlink:href="#icon-phone" fill="red"></use>
</svg>

svg封装为全局组件

因为项目很多模块需要使用图标,因此把它封装为全局组件!!!

在src/components目录下创建一个SvgIcon组件:代表如下

<template>
  <div>
    <svg :style="{ width: width, height: height }">
      <use :xlink:href="prefix + name" :fill="color"></use>
    </svg>
  </div>
</template>

<script setup lang="ts">
defineProps({
  //xlink:href属性值的前缀
  prefix: {
    type: String,
    default: '#icon-'
  },
  //svg矢量图的名字
  name: String,
  //svg图标的颜色
  color: {
    type: String,
    default: ""
  },
  //svg宽度
  width: {
    type: String,
    default: '16px'
  },
  //svg高度
  height: {
    type: String,
    default: '16px'
  }

})
</script>
<style scoped></style>

src/components文件夹目录下创建一个index.ts文件:用于注册components文件夹内部全部全局组件!!!

import SvgIcon from './SvgIcon/index.vue';
import type { App, Component } from 'vue';
const components: { [name: string]: Component } = { SvgIcon };
export default {
    install(app: App) {
        Object.keys(components).forEach((key: string) => {
            app.component(key, components[key]);
        })
    }
}

在入口文件main.ts引入src/index.ts文件,通过app.use方法安装自定义插件,把组件进行全局注册

import gloablComponent from './components/index';
app.use(gloablComponent);

页面中使用:

<svg-icon name="logout" color="pink" width="100px" height="100px"></svg-icon>

如果遇到设置了颜色不生效,或者部分生效的问题,可以使用编辑器打开svg文件:

处理办法:把svg文件中的 fill 属性,删除即可(svg文件中的 fill 属性是无法修改的)

报错

报错:Cannot find package ‘fast-glob‘,安装下对应依赖就可以了

npm install fast-glob -D