Vue3.2 +Vite添加Svg的使用
1. 安装依赖插件vite-plugin-svg-icons
yarn add vite-plugin-svg-icons -D
目前使用的版本是1.1.0
2. 配置vite.config.ts
iconDirs
所有的 svg的文件都存放在该文件夹下symbolId
指定use
标签中href
格式
import { defineConfig } from 'vite'
import { resolve } from 'path'
import vitePluginSvgIcons from 'vite-plugin-svg-icons'
export default defineConfig(()=>{
return {
plugins: [
// 引入 svg
vitePluginSvgIcons({
iconDirs: [resolve(__dirname, 'src/assets/icon/svg')], // 所有的 svg的文件都存放在该文件夹下
symbolId: 'icon-[name]'
}),
],
}
})
3. 封装使用全局组件
html
部分<template> <svg aria-hidden="true"> <use :href="symbolId" /> </svg> </template>
js
部分<script setup lang="ts"> import { computed } from 'vue' interface IProps { /** svg 的图标的名称 */ iconName: string } const props = defineProps<IProps>() const symbolId = computed(()=> `#icon-${props.iconName}`) </script>
- 注册全局组件
import { App } from 'vue' app.component('SvgIcon', SvgIcon)
- 使用,这里的
icon-name
中必须要和assets/icon/svg
中的svg
文件名称保持一致<SvgIcon icon-name="wechat" />
- 效果图
4. 如果使用的vite-plugin-svg-icons
是2.x
的版本, 需要修改
- 首先是
vite.config.ts
需要导入的地方修改未为import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import { defineConfig } from 'vite'
import { resolve } from 'path'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
export default defineConfig(()=>{
return {
plugins: [
// 引入 svg
createSvgIconsPlugin({
iconDirs: [resolve(process.cwd(), 'src/assets/icon/svg')],
symbolId: 'icon-[name]'
}),
]
}
})
- 还需要在
main.ts
中导入
import 'virtual:svg-icons-register'