vue3+ts+vite项目中使用vite-plugin-svg-icons插件处理svg
1.安装依赖:npm install vite-plugin-svg-icons -D
2.vite.config.ts 中配置:
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons' // 在export default ({ command, mode }: ConfigEnv): UserConfig中的plugins数组中添加代码 plugins: [ createSvgIconsPlugin({ // 指定需要缓存的图标文件夹,地址可改 iconDirs: [path.resolve(process.cwd(), 'src/assets/svg')], // 指定symbolId格式 symbolId: 'icon-[dir]-[name]', }) ],
3.main.ts中添加代码:
import 'virtual:svg-icons-register'
4.在components创建SvgIcon.vue组件
<script lang="ts" setup> defineProps({ name: { type: String, required: true, default: 'car', }, size: { type: Number, default: 30, }, color: { type: String, default: '#000', }, }) </script> <template> <svg class="svg-icon" :style="{ width: `${size}px`, height: `${size}px`, color: `${color}` }"> <use :xlink:href="`#icon-${name}`" :fill="color" /> </svg> </template>
5.在main.ts中全局引用
import svgIcon from './components/SvgIcon.vue' const app = createApp(App) app.component('SvgIcon', svgIcon)
6.在src/assets文件价下新建svg文件夹,将下载的svg文件放在这个文件夹下
7.在组件中使用
<svg-icon name="airService" :size="16" />
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了