vite-plugin-svg-icons 使用SVG图片

424 阅读1分钟

安装

npm i vite-plugin-svg-icons -D

在main.js引入

import 'virtual:svg-icons-register'

在vite.config.js中配置

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

export default () => {
	return {
		plugins: [
			createSvgIconsPlugin({
					iconDirs: [path.resolve(process.cwd(), 'src/assets/icon-svg/')],
					symbolId: 'icon-[name]',
				}),
		]
	}
}

写个icon组件

components/SvgIcon/index.vue

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

<script>
import { defineComponent, computed } from "vue";
export default defineComponent({
  props: {
    iconClass: {
      type: String,
      required: true,
    },
    className: {
      type: String,
      default: "",
    },
    color: {
      type: String,
      default: "",
    },
  },
  setup(props) {
    return {
      iconName: computed(() => `#icon-${props.iconClass}`),
      svgClass: computed(() => {
        if (props.className) {
          return `svg-icon ${props.className}`;
        }
        return "svg-icon";
      }),
    };
  },
});
</script>

<style scope >
.svg-icon {
  width: 1em;
  height: 1em;
  position: relative;
  fill: currentColor;
  vertical-align: -2px;
}
</style>

按需引入使用

<template>
  <SvgIcon iconClass="issue"></SvgIcon>
</template>

<script setup>
import SvgIcon from "./components/SvgIcon/index.vue";
</script>

全局引入使用

// main.ts

import SvgIcon from "./components/SvgIcon/index.vue";

....
app.component('svg-icon', SvgIcon);

error

// Cannot find package 'fast-glob' imported from
pnpm install fast-glob --save