之前写过一个element-plus icon组件的批量注册(element-plus/icons 批量注册,菜单路由icon图标设置_失岸的博客-CSDN博客_element菜单图标),但项目中往往还需要一些其他的图标,该方法可以在引入svg文件时通过传入icon名字即可直接渲染
1.新建icon文件夹
2. 新建一个SvgIcon.vue 和一个js文件
index.vue
<template>
<svg :class="svgClass" aria-hidden="true" v-bind="$attrs">
<use :xlink:href="iconName"/>
</svg>
</template>
<script setup>
import { computed, defineProps } from 'vue'
const props = defineProps({
name: {
type: String,
required: true
}
})
const iconName = computed(() => `#icon-${props.name}`)
const svgClass = computed(() => {
if (props.name) {
return `wb-icon svg icon-${props.name}`
}
return 'wb-icon svg'
})
</script>
<style lang="less" scoped>
.wb-icon.svg {
width: 1em;
height: 1em;
fill: currentColor;
overflow: hidden;
vertical-align: middle;
}
</style>
svgBuilder.js
import { readFileSync, readdirSync } from 'fs'
let idPerfix = ''
const svgTitle = /<svg([^>+].*?)>/
const clearHeightWidth = /(width|height)="([^>+].*?)"/g
const hasViewBox = /(viewBox="[^>+].*?")/g
const clearReturn = /(\r)|(\n)/g
function findSvgFile(dir) {
const svgRes = []
const dirents = readdirSync(dir, {
withFileTypes: true
})
for (const dirent of dirents) {
if (dirent.isDirectory()) {
svgRes.push(...findSvgFile(dir + dirent.name + '/'))
} else {
const svg = readFileSync(dir + dirent.name)
.toString()
.replace(clearReturn, '')
.replace(svgTitle, ($1, $2) => {
let width = 0
let height = 0
let content = $2.replace(clearHeightWidth, (s1, s2, s3) => {
if (s2 === 'width') {
width = s3
} else if (s2 === 'height') {
height = s3
}
return ''
})
if (!hasViewBox.test($2)) {
content += `viewBox="0 0 ${width} ${height}"`
}
return `<symbol id="${idPerfix}-${dirent.name.replace(
'.svg',
''
)}" ${content}>`
})
.replace('</svg>', '</symbol>')
svgRes.push(svg)
}
}
return svgRes
}
export const svgBuilder = (path, perfix = 'icon') => {
if (path === '') return
idPerfix = perfix
const res = findSvgFile(path)
return {
name: 'svg-transform',
transformIndexHtml(html) {
return html.replace(
'<body>',
`
<body>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="position: absolute; width: 0; height: 0">
${res.join('')}
</svg>
`
)
}
}
}
4.vite.cinfig.js 配置文件
import { svgBuilder } from './src/components/SvgIcon/svgBuilder'
svgBuilder('./src/assets/icon/') // svg图标批量引入
5.使用
<SvgIcon name="lang" style="color:#fff;font-size:18px;"/>
6.效果
github项目地址: https://github.com/jimoruyan/vite-vue3-template
gitee项目地址:windmoon/vite-vue3-temptale
如果对您有帮助还请贡献一个star