npm install svg-sprite-loader
yarn add svg-sprite-loader
-
创建需要使用到的文件(目录)
这边我是在src目录下的components文件下创建的svgIcon文件夹,svgIcon文件夹内创建index.vue文件和svgFn.ts文件,分别放置组件和核心ts代码,另外创建一个svg-icons文件夹用来放置.svg文件
- index.vue文件代码
<template>
<svg
:class="svgClass"
v-bind="$attrs"
:style="{ color: color, width: w, height: h }"
>
<use :xlink:href="iconName"></use>
</svg>
</template>
<script setup lang="ts">
import { computed, defineProps } from "vue";
/*
* name 名字 必填
* color 颜色
* w 宽度
* h 高度
*/
const props = defineProps({
name: {
type: String,
required: true,
},
color: {
type: String,
default: "",
},
w: {
type: String,
default: "1rem",
},
h: {
type: String,
default: "1rem",
},
});
console.log(props.name, props.color);
const iconName = computed(() => `#icon-${props.name}`);
const svgClass = computed(() => {
if (props.name) return `svg-icon icon-${props.name}`;
return "svg-icon";
});
</script>
<style scoped>
.svg-icon {
/* 此属性为更改svg颜色属性设置 */
fill: currentColor;
vertical-align: middle;
}
</style>
import { readFileSync, readdirSync } from 'fs'
let idPerfix = ''
const svgTitle = /<svg([^>+].*?)>/
const clearHeightWidth = /(width|height)="([^>+].*?)"/g
const hasViewBox = /(viewBox="[^>+].*?")/g
const clearReturn = /(\r)|(\n)/g
// 查找svg文件
const svgFind = (e: any): any => {
const arr = []
const dirents = readdirSync(e, { withFileTypes: true })
for (const dirent of dirents) {
if (dirent.isDirectory()) arr.push(...svgFind(e + dirent.name + '/'))
else {
const svg = readFileSync(e + dirent.name)
.toString()
.replace(clearReturn, '')
.replace(svgTitle, ($1, $2) => {
let width = 0,
height = 0,
content = $2.replace(clearHeightWidth, (s1: any, s2: any, s3: any) => {
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>')
arr.push(svg)
}
}
return arr
}
// 生成svg
export const createSvg = (path: any, perfix = 'icon') => {
if (path === '') return
idPerfix = perfix
const res = svgFind(path)
return {
name: 'svg-transform',
transformIndexHtml(dom: String) {
return dom.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>`
)
}
}
}
- 在 main.ts文件中设置svg-icon为全局组件
import { createApp } from 'vue'
import svgIcon from '@/components/svgIcon/index.vue'
import App from './App.vue'
const app = createApp(App)
app.component('svg-icon', svgIcon)
app.mount('#app')
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
//引入核心ts文件
import { createSvg } from './src/components/svgIcon/svgFn'
export default defineConfig({
plugins:[{
vue(),
//路径指向 .svg 文件夹
createSvg('./src/components/svgIcon/svg-icons/')
}]
})
<svg-icon name="admin" color="#0094ff"></svg-icon>
记录完毕!参考文章 、参考文章