yarn add svg-sprite-loader -D
// 或者
npm install svg-sprite-loader -D
复制代码
在@/src
里面建立icons
文件夹,里面建立index.vue
(svgicon的模板文件), index.ts
(svgicon的js逻辑), svg文件夹
(svg图标存放的地址)vue
这部分须要用到fs模块,因此须要:npm
yarn add fs
// 或者
npm install fs
复制代码
<template>
<svg :class="svgClass" v-bind="$attrs" :style="{ color: color }">
<use :xlink:href="iconName"></use>
</svg>
</template>
<script setup lang="ts">
import { computed, defineProps } from 'vue'
const props = defineProps({
name: {
type: String,
required: true
},
color: {
type: String,
default: ''
}
})
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{width: 1em;height: 1em;fill:currentColor; vertical-align: middle;}
</style>
复制代码
这部分有问题的小伙伴能够找我,我写了注释的。markdown
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文件
function svgFind(e) {
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, 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>')
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>`
)
}
}
}
复制代码
import { defineConfig } from "vite"
import { createSvg } from './src/icons/index'
export default defineConfig({
plugins: [
vue(),
createSvg('./src/icons/svg/')
]
})
复制代码
svg-icon
模板import { createApp } from 'vue'
import App from './App.vue'
import svgIcon from './icons/index.vue'
const app = createApp(App)
app
.component('svg-icon', svgIcon)
.mount('#app')
复制代码
公众号:
小何成长
,佛系更文,都是本身曾经踩过的坑或者是学到的东西app有兴趣的小伙伴欢迎关注我哦,我是:
何小玍。
你们一块儿进步鸭dom