vue3+ts+vite使用vite-plugin-svg-icons

313 阅读1分钟

第一步:

  1. 首先下载vite-plugin-svg-icons

  2. main.ts

import 'virtual:svg-icons-register'
  1. vite.config.ts
export default defineConfig({
  plugins: [
    vue(),
    createSvgIconsPlugin({
      iconDirs: [path.resolve(process.cwd(), "src/assets/svgIcon")], // icon存放的目录
      symbolId: "icon-[name]", // symbol的id
      inject: "body-last", // 插入的位置
      customDomId: "__svg__icons__dom__" // svg的id
    }),
  ],
  ...
  ...
})
  1. 然后先运行项目查看是否报错,如果有fast-glob错误,那就再下载fast-glob

第二步:

  1. src/assets目录下新建文件夹存放svg文件如下图

image.png

  1. src/utils目录下新建 requireIcons.ts 文件
const req = import.meta.glob('@/assets/svgIcon/**/*.svg')

const icons = Object.keys(req).map(item => {
  let arr = item.split('/')
  return arr[arr.length - 1].slice(0, -4)
})

export default icons
  1. 在src/components目录下新建 svgIcon.vue 文件
<template>
    <div v-if="isExternal" :style="styleExternalIcon" class="svg-external-icon svg-icon" v-bind="$attrs"></div>
    <svg v-else :class="svgClass" aria-hidden="true" v-bind="$attrs">
        <use :href="iconName" />
    </svg>
</template>

<script setup lang="ts">
import { reactive, toRefs, computed } from "vue";

const props = defineProps({
    iconClass: {
            type: String,
            required: true,
    },
    className: {
            type: String,
            default: "",
    },
});

let data = reactive({
    isExternal: /^(http?:|https?:|mailto:|tel:)/.test(props.iconClass),
    styleExternalIcon: {
        mask: `url(${props.iconClass}) no-repeat 50% 50%`,
        "-webkit-mask": `url(${props.iconClass}) no-repeat 50% 50%`,
    },
});
const iconName = computed(() => {
    return `#icon-${props.iconClass}`;
});
const svgClass = computed(() => {
    return props.className ? "svg-icon " + props.className : "svg-icon";
});
const { isExternal, styleExternalIcon } = toRefs(data);
</script>

<style scoped>
.svg-icon {
    width: 1em;
    height: 1em;
    vertical-align: -0.15em;
    fill: currentColor;
    overflow: hidden;
}

.svg-external-icon {
    background-color: currentColor;
    mask-size: cover !important;
    display: inline-block;
}
</style>
  1. main.ts中全局引入svgIcon组件
import SvgIcon from "@/components/svgIcon.vue";
const app = createApp(App)
app.component('SvgIcon', SvgIcon)

然后就可以在vue组件中使用该组件了

<SvgIcon :iconClass="'404'"></SvgIcon>