利用svg-sprite-loader插件
1.安装依赖
pnpm i svg-sprite-loader
2.配置需要加载的svg位置,以及真实svg标签在dom中的位置等
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: string, perfix = 'icon'): any => {
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>
`
)
}
}
}
3.在vite.config.js中注册
plugins: [
...,
svgBuilder('./src/assets/icon/svg/') // 这里添你放icon的位置
],
4.封装svg-icon组件
<template>
<svg :class="svgClass" v-bind="$attrs">
<use :href="svgName"></use>
</svg>
</template>
<script setup>
import { computed } from "vue"
const props = defineProps({
//图标名称 如 home
iconName: {
type: String,
default: ""
},
//对不同区域的 icon 样式调整,如字体大小
className: {
type: String,
default: ""
}
})
const svgName = computed(() => `#icon-${props.iconName}`)
const svgClass = computed(() => {
if (props.className) {
return `svg-icon ${props.className}`
}
return `svg-icon`
})
</script>
<style>
.svg-icon {
width: 1em;
height: 1em;
vertical-align: -0.15em;
fill: currentColor; /*此属性为更改svg颜色属性设置*/
overflow: hidden;
}
</style>
- 在main.ts全局注册(你也可以按需引入)
const app = createApp(AppMain)
app.component('svg-icon', SvgIcon)
利用vite-plugin-svg-icons插件,将多个svg文件导入为一个精灵图,实现单请求获取文件
1.安装组件库 pnpm add vite-plugin-svg-icons -D官方文档
2.在vite.config.js中配置插件
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import path from 'path'
export default defineConfig({
plugins: [
createSvgIconsPlugin({
iconDirs: [path.resolve(process.cwd(), 'src/icons')]
})
]
})
3.在main.js中导入
import 'virtual:svg-icons-register'
4.封装svg组件
// aria-hidden是朗读等需要查询页面文字功能时,隐藏,用于残障人士阅读时不混淆
<template>
<svg aria-hidden="true" class="my-icon">
<use :href="`svg-${name}`"></use>
</svg>
</template>
<script setup>
defineProps({
name:string
})
</script>
<style scoped>
.my-icon {
// 和 font-size 一样大
width: 1em;
height: 1em;
}
</style>