vue3+vite2中使用svg(亲测可用)

无聊才收藏 关注

收藏于 : 2022-08-10 10:34   被转藏 : 1   

技术栈:vue3+vite2
前言:写过一版基于vue-cli中使用svg的方法,但是因为webpack提供了require.context()在vite中无法使用,所以基于vite构建的项目则采取另一种方法

一、安装vite-plugin-svg-icons

此处还需要安装下fast-glob相关依赖,不然vite运行npm run dev时会报Cannot find module 'fast-glob’的错误


npm i fast-glob@3.x -D
npm i vite-plugin-svg-icons@2.x -D


二、在src/components/svgIcon下新建组件index.vue


<template>
  <svg aria-hidden="true" >
    <use :xlink:href="symbolId" :fill="color" />
  </svg>
</template>

<script setup lang="ts">
import { computed } from 'vue';

const props = defineProps({
  prefix: {type: String,default: 'icon',},
  iconClass: {type: String,required: true,},
  color: {type: String,default: ''}
})

const symbolId = computed(() => `#${props.prefix}-${props.iconClass}`);
</script>

<style scoped>
.svg-icon {
  width: 1em;
  height: 1em;
  vertical-align: -0.15em;
  overflow: hidden;
  fill: currentColor;
}
</style>


三、tsconfig.json中添加设置

types用来指定需要包含的模块,只有在这里列出的模块的声明文件才会被加载进来。非必要添加,我在两个demo测试的时候,一个需要一个不需要,若有问题可以尝试添加


{
  "compilerOptions": {
    "types": ["vite-plugin-svg-icons/client"]
  }
}


四、vite.config.ts 中的配置插件

import { resolve } from 'path'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'

export default defineConfig({
  plugins: [
    createSvgIconsPlugin({
      // 指定需要缓存的图标文件夹
      iconDirs: [resolve(process.cwd(), 'src/assets/imgs/svg')],
      // 指定symbolId格式
      symbolId: 'icon-[dir]-[name]',
    })
  ]
})


五、在main.ts全局注册组件


import { createApp } from 'vue'
import App from './App.vue'
import router from '@/router'
import { store, key } from '@/store'

const app = createApp(App)

import 'virtual:svg-icons-register' // 引入注册脚本
import SvgIcon from '@/components/svgIcon/index.vue' // 引入组件
app.component('svg-icon', SvgIcon)

app.use(router).use(store, key).mount('#app')


六、在页面中使用


<template>
  <svg-icon icon-></svg-icon>
  <svg-icon icon- ></svg-icon>
</template>


七、文件目录结构及其效果展示

八、参考链接地址

1、依赖官方参考文档:https://github.com/vbenjs/vite-plugin-svg-icons/blob/main/README.zh_CN.md
2、其中有一些内容点我根据该文章进行参考:https://www.cnblogs.com/haoxianrui/archive/2022/04/02/16090029.html
3、在vue-cli中使用svg的可以参考我另一篇文章:https://blog.csdn.net/blackhub/article/details/123707917


 阅读文章全部内容  
点击查看
文章点评
相关文章
无聊才收藏 关注

文章收藏:17

TA的最新收藏