如何在Vite Vue项目中引入使用SVG图标?

摘要:在写前端的时候觉得 Element Plus 的图标库不够或不是很符合,想要使用自定义的图标,但是又不想引入额外的图标库,这时候就可以使用 Svg 图标,这篇文章就是介绍如何在 Vite + Vue 中使用 Svg 图标。
在写前端的时候觉得 Element Plus 的图标库不够或不是很符合,想要使用自定义的图标,但是又不想引入额外的图标库,这时候就可以使用 Svg 图标,这篇文章就是介绍如何在 Vite + Vue 中使用 Svg 图标。以及封装成组件使用。 初始化项目 首先我们需要初始化一个 Vite + Vue + TS 的项目,这里使用 pnpm 作为包管理工具,当然你也可以使用 npm 或者 yarn。 pnpm create vite svg-example --template vue-ts cd svg-example pnpm install pnpm run dev 添加 Svg 插件 创建项目后会有一个 vue 的图标,我们就使用这个图标来展示。 我们需要安装一个插件来处理 Svg 文件,这里使用 @tangllty/vite-plugin-svg。 pnpm install @tangllty/vite-plugin-svg -D 然后在 vite.config.ts 中添加插件。 import { svgIconsPlugin } from '@tangllty/vite-plugin-svg' export default defineConfig({ plugins: [ svgIconsPlugin({ pattern: 'src/assets/**/*.svg', }) ] }) 创建 Svg 组件 我们需要创建一个 Svg 组件来展示 Svg 图标。 <template> <svg aria-hidden="true" class="svg-icon" :style="`width: ${size}; height: ${size};`" > <use :href="symbolId" :fill="color" /> </svg> </template> <script lang="ts" setup> import { computed } from 'vue' const props = defineProps({ prefix: { type: String, default: 'icon' }, name: { type: String, required: false }, color: { type: String }, size: { type: String, default: '1em' } }) const symbolId = computed(() => `#${props.prefix}-${props.name}`) </script> <style scoped> .svg-icon { overflow: hidden; fill: currentColor; } </style> 使用 Svg 组件 我们在 App.vue 中使用 Svg 组件。 <template> <div id="app"> <SvgIcon name="vue" size="16em" /> </div> </template> <script lang="ts" setup> import SvgIcon from './components/SvgIcon/index.vue' </script> 效果如下: 插件地址: GitHub Gitee NPM