1.下载插件
cnpm i vite-plugin-svg-icons -D
2.在vite.config.ts中配置svg
import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import path from 'path'
//引入svg此插件 cnpm i vite-plugin-svg-icons -D
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
vue(),
vueJsx(),
createSvgIconsPlugin({
iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')], //取svg的文件路径
symbolId: 'icon-[dir]-[name]',
}),
],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url)),
},
},
})
3.封装svg组件
<template>
<!-- svg 结合use 使用 -->
<svg :style="{ width, height }">
<use :xlink:href="prefix + name" :fill="color"></use>
</svg>
</template>
<script setup lang="ts">
//接收父组件传递过来的参数
defineProps({
// xlink:href 属性值前缀
prefix: {
type: String,
default: '#icon-',
},
// //接收父组件传递的名字
name: {
type: String,
default: '',
},
//接收父组件传递的颜色
color: {
type: String,
default: '',
},
//接收父组件传递的图标的宽度
width: {
type: String,
default: '16px',
},
//接收父组件传递的图标的高度
height: {
type: String,
default: '16px',
},
})
</script>
4.全局注册组件 (在components下新建文件index.ts)
//引入全局组件
import SvgIcon from './SvgIcon/index.vue'
//我这里使用的ui 框架时arco-vue //根据实际取使用
//全局映入aroc-vue icon
import ArcoVueIcon from '@arco-design/web-vue/es/icon'
//全局对象
const allGloabComponent = { SvgIcon }
// 暴露全局组件
export default {
install(app: any) {
//循环注入
Object.keys(allGloabComponent).forEach((item) => {
app.component(item, allGloabComponent[item])
})
//将element icon 注册全局
for (const [key, component] of Object.entries(ArcoVueIcon)) {
app.component(key, component)
}
},
}
5.在main.ts中引入
//引入自定义全局组件
import globalComponents from '@/components'
app.use(globalComponents)
6.使用
<SvgIcon name="phone" color="red" width="50px" height="50px" />
//name 是你svg的名称