1.下载svg依赖
pnpm i vite-plugin-svg-icons -D
还有一个,下面的不安装可能会报错
pnpm i fast-glob -D
2.vite.config.ts配置
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from "path";
//引入svg需要用到的插件
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
export default defineConfig({//TODOplugins: [vue() , createSvgIconsPlugin({iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],symbolId: 'icon-[dir]-[name]'})],//ENDresolve:{alias:{"@":path.resolve(__dirname , "./src"),}}
})
3.main.ts配置
import { createApp } from 'vue'
import App from './App.vue'
//引入element-plus插件与样式
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
///
//引入element-plus国际化
//忽略当前文件ts类型检测,要不然打包会失败
//@ts-ignore
import zhCn from 'element-plus/es/locale/lang/zh-cn.mjs'//TODO
//引入svg配置文件
import 'virtual:svg-icons-register'//引入自定义插件对象:注册整个项目全局组件
import globalComponent from '@/components'
createApp(App).use(ElementPlus,{ locale: zhCn }).use(globalComponent).mount('#app')
//END
4.文件夹创建
assets -> icons -> ...svg
assets里面创建icons文件夹,里面放.svg矢量图标(记得去色)
5.SvgIcon组件
components -> SvgIconG -> index.vue
<template><svg :style="{ width , height }"><use :xlink:href="prefix + name" :fill="color"></use></svg>
</template><script setup lang='ts'>
defineProps({name: {type: String,}, width: {type: String,default: '1em'}, height: {type: String,default: '1em'}, color: {type: String,default: '#333'}, prefix: {type: String,default: '#icon-'}
})
</script><style scoped lang="scss"></style>
6.自定义注册全局插件
components里面创建index.ts
import SvgIconG from './SvgIconG/index.vue';
import ... from '...';
//全局对象
const allGlobalComponents :any = { SvgIconG , ... }
export default {install(app : any){Object.keys(allGlobalComponents).forEach(key => {app.component(key, allGlobalComponents[key]);})}
}
然后在main.ts里面注册就行(方法在上面main.ts里面)