1.安装vite-plugin-svg-icons
npm i vite-plugin-svg-icons -D
2. 新建文件夹 src/assets/icons/svg来存放svg 图片
3.新建组件src/components/SvgIcon/index.vue
<template>
<svg :style="{width, height}">
<use :xlink:href="prefix + name" :fill="color"></use>
</svg>
</template>
<script setup lang="ts">
defineProps({
//前缀
prefix: {
type: String,
default: "#icon-"
},
//图标名称
name: String,
//颜色
color: {
type: String,
default: "#fff"
},
width: {
type: String,
default: "20px"
},
height: {
type: String,
default: "20px"
},
})
</script>
<style scoped></style>
4. 注册 新建src/assets/icons/index .vue
import SvgIcon from '@/components/SvgIcon/index.vue';
import type { App, Component } from 'vue';
const components: { [name: string]: Component } = { SvgIcon };
export default {
install(app: App) {
Object.keys(components).forEach((key: string) => {
app.component(key, components[key]);
})
}
}
5.vite.config.ts中配置
export default defineConfig({
//静态资源服务的文件夹
publicDir: 'public',
base: './',
plugins: [
vue(),
createSvgIconsPlugin({//svg配置
// iconDirs: [path.resolve(process.cwd(),'src/assets/icons/svg')],//导入路径为'src/assets/icons'
iconDirs: [fileURLToPath(new URL('src/assets/icons/svg', import.meta.url))],//导入路径为'src/assets/icons'
symbolId: 'icon-[dir]-[name]',//名称格式为‘icon-name’格式
})
],
...
})
6.main.ts 中配置
import IconComponents from '@/assets/icons'
//svg插件在主文件内需要的配置代码
import 'virtual:svg-icons-register'
...
InitCustomConfig().then(config => {
const app = createApp(App).use(IconComponents)
app.mount('#app')
...
})
7.直接使用
<svg-icon name="login-password"></svg-icon>