安装
yarn add vite-plugin-svg-icons -D
在vite.config.ts中使用
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
//自定义常量
/**svg地址 */
//const SVG_PATH = path.join(__dirname, '../src/assets/svg')
import { SVG_PATH } from './constant'
...plugin:[
createSvgIconsPlugin({
iconDirs: [SVG_PATH],
symbolId: 'icon-[dir]-[name]'
}),
]
在main.ts中引入 virtual:svg-icons-register
import 'virtual:svg-icons-register' //不引入不能生效
封装svg组件
<!--
* @Description: svg组件 结合 vite-plugin-svg-icons使用
* @Author: HYH
* @LastEditors: HYH
* @LastEditTime: 2022-08-18 17:00:23
-->
<script setup lang="ts">
defineProps<{ name: string; className?: string }>()
</script>
<template>
<svg class="svg-style" :class="className">
<use :href="'#icon-' + name"></use>
</svg>
</template>
<style lang="scss" scoped>
.svg-style {
width: 100px;
height: 100px;
}
</style>
注册组件
import components from '@/components/index'
// 注册全局的组件
for (const componentItme in components) {
uiApp.component(componentItme, components[componentItme])
}
页面使用
<!--
* @Description:
* @Author: HYH
* @LastEditors: HYH
* @LastEditTime: 2022-08-18 16:44:46
-->
<script setup lang="ts"></script>
<template>
<Svg name="" class-name="" />
</template>
<style lang="scss" scoped>
</style>