插件: vite-plugin-svg-icons
官方文档
https://github.com/vbenjs/vite-plugin-svg-icons/blob/main/README.zh_CN.md
- 安装
yarn add vite-plugin-svg-icons -D
# or
npm i vite-plugin-svg-icons -D
# or
pnpm install vite-plugin-svg-icons -D
- VITE配置
// vite-plugin-svg-icons
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import path from 'path'
// https://vitejs.dev/config/
export default defineConfig({
// ...
plugins: [
// svg 加载
createSvgIconsPlugin({
// 指定需要缓存的图标文件夹 根据实际配置 svg必须在文件夹下
iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],
// 指定symbolId格式
symbolId: 'icon-[dir]-[name]',
/**
* 自定义插入位置
* @default: body-last
* @options body-last | 'body-first'
*/
inject: 'body-last',
/**
* custom dom id
* @default: __svg__icons__dom__
*/
customDomId: '__svg__icons__dom__'
})
],
})
- main.js / ts
在 src/main.ts 内引入注册脚本
// eslint-disable-next-line import/no-unresolved
import 'virtual:svg-icons-register'
// eslint 会报错 可在.eslintrc.cjs 中关闭 或者 建议上面单次注释
'import/no-unresolved': 'off',
此时已经完成了基础配置,如何在组件中使用呢?
假设这么个目录结构
src
/assets
/icons
- name/other.svg
- user.svg
- pwd.svg
- 基础使用
<svg aria-hidden="true">
<!-- #icon-文件夹名称-图片名称 -->
<!--#icon必须 pwd是svg文件名 -->
<use href="#icon-pwd" /> pwd.svg
<use href="#icon-user" /> user.svg
<use href="#icon-name-other" /> other.svg
</svg>
- 封装组件
<template>
<svg aria-hidden="true" class="svg-icon">
<use :xlink:href="symbolId" :fill="color" />
</svg>
</template>
<script setup lang="ts">
import { computed } from 'vue'
const props = defineProps<{
name: string
color?: string
}>()
const symbolId = computed(() => `#icon-${props.name}`)
</script>
<style lang="less" scoped>
.svg-icon {
width: 1em;
height: 1em;
vertical-align: -0.15em;
fill: currentColor;
overflow: hidden;
}
</style>
- 组件使用
<svgIcon name="pwd" :color="'#0000ff'" style="width: 20px; height: 20px; "></svgIcon>
import svgIcon from '@/components/SvgIcons/index.vue'
以上
– END –