- 首先创建一个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, (_, $2) => {
let width = 0
let height = 0
let content = $2.replace(clearHeightWidth, (_, 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>
`,
)
},
}
}
- 在
vite.config.js
中导入svgBuilder.js
plugins: [
vue(),
[svgBuilder('./src/assets/svg/')] // 这里已经将src/icons/svg/下的svg全部导入,无需再单独导入
]
- 创建一个svg-icon组件
<template>
<div :title="title" class="container-icon" :style="{width: iconSize + 'px',height: iconSize + 'px',}">
<svg :class="['svg-icon', $attrs.class]" :style="{width: iconSize + 'px',height: iconSize + 'px',}" aria-hidden="true">
<use :xlink:href="'#icon-' + iconName" :fill="color" :title="title"/>
</svg>
</div>
</template>
<script>
import { defineComponent } from 'vue'
export default defineComponent({
name: 'SvgIcon',
props: {
iconName: {
type: String,
required: true,
},
color: {
type: String,
default: '',
},
title: {
type: String,
default: '',
},
iconSize: {
type: [Number, String],
default: 14,
},
},
setup () {
return {}
},
})
</script>
<style scoped>
.container-icon{
display: inline-block;
margin: 0 5px;
}
.svg-icon {
vertical-align: middle;
fill: currentColor;
display: block;
}
</style>
- 在
main.js
中引入svg-icon
import SvgIcon from './components/svg-icon.vue'
const app = createApp(App)
app.component('SvgIcon', SvgIcon)
app.mount('#app')
- 使用
<SvgIcon :iconName="'icon-upload'" @click="handleUpload(scope.row)" :iconSize="20"></SvgIcon>