安装依赖
pnpm i vite-plugin-svg-icons -D
配置引入
vite.config.ts
...
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import path from 'node:path'
const svgIconsPlugin = createSvgIconsPlugin({
iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],
symbolId: 'icon-[dir]-[name]', // 支持目录层级:'icon-[dir]-[name]'
inject: 'body-last', // DOM插入位置
customDomId: '__svg_icons' // 自定义容器ID
})
// https://vite.dev/config/
export default defineConfig({
plugins: [
...,
svgIconsPlugin,
],
...,
})
main.ts
// svg 图标插件模块引入
import 'virtual:svg-icons-register'
应用
简单应用
- 在
src/assets/目录下创建icons文件夹 - 在网上找到想要使用的
svg图标,复制其svg代码 - 在之前创建的
icons文件夹下创建xxx.svg文件 - 粘贴复制的
svg代码到xxx.svg文件里
<template>
<svg style="width: 16px; height: 16px">
//#icon-svg文件名 fill字段 指定图标颜色
<use xlink:href="#icon-add" fill="red"></use>
</svg>
</template>
add代表的是创建的svg文件名
参考地址:blog.csdn.net/lawidn56/ar…
封装成组件
-
准备
svg文件到目录src/assets/icons/ -
创建组件目录文件
src/components/SvgIcon/index.vue<template> <svg :style="{ width, height }"> <use :xlink:href="prefix + name" :fill="color" /> </svg> </template> <script setup lang="ts"> // 接收父组件传递过来的参数 defineProps({ // 图标前缀(xlink:href属性值前缀) prefix: { type: String, default: '#icon-' }, // 图标名称 name: String, // 图标颜色 color: { type: String, default: '#333' }, // 图标大小 width: { type: String, default: '16px' }, height: { type: String, default: '16px' } }) </script> -
使用组件 xxx.vue
<template> <svg-icon width="32" height="32" name="home" color="red"></svg-icon> </template> <script setup lang="ts"> import SvgIcon from '@/components/SvgIcon/index.vue' </script>
注册全局组件
- 简单注册:
main.ts中注册全局组件,其他 vue 文件直接使用
const app = createApp(App)
// 注册 svg 图标全局组件
import SvgIcon from '@/components/SvgIcon/index.vue'
app.component('SvgIcon', SvgIcon)
app.mount('#app')
- 多个组件注册
src/components/下创建index.ts文件main.ts中注册全局组件- vue 文件直接使用
src/components/index.ts
// 引入所有组件
import SvgIcon from './SvgIcon/index.vue'
import Xxx from './Xxx/index.vue'
import type { App, Component } from 'vue'
// 引入所有组件,统一注册
const allGlobalComponent: Record<string, Component> = {
SvgIcon,
Xxx
}
// 对外暴露插件对象
export default {
// 必须叫做 install 方法
install(app: App) {
// 遍历所有自定义组件
Object.keys(allGlobalComponent).forEach(key => {
// 注册为全局组件
app.component(key, allGlobalComponent[key])
})
}
}
main.ts
const app = createApp(App)
// 引入自定义插件对象,注册整个项目全局组件
import globalComponent from '@/components';
// 安装自定义插件
app.use(globalComponent); // 会触发全局组件的 install 方法
app.mount('#app')