项目结构
1. 首先引入svg插件
yarn add svg-sprite-loader -D // 或者 npm install svg-sprite-loader -D
2. 创建文件
1、创建icons
文件夹,里面创建 index.ts
(svgicon的js逻辑), svg文件夹
(svg图标存放的地址)
》》index.ts
const {readFileSync, readdirSync} = require('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 } const createSvg = (path, perfix = 'icon') => { if (path === '') return idPerfix = perfix const res = svgFind(path) return { name: 'svg-transform', transformIndexHtml(dom) { 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>` ) } } } // 生成svg module.exports = createSvg
2、创建组件里面index.vue
(svgicon的模板文件)
》》SvgIcon.vue
<template> <svg :class="svgClass" v-bind="$attrs" :style="{ color: color }"> <use :xlink:href="iconName" /> </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>
3、vite.config.js配置文件加上index.ts的引用:
createSvg('src/renderer/assets/icons/svg/')
// ... const createSvg = require('../src/renderer/assets/icons/index.ts') // ... const config = defineConfig({ // ... plugins: [ // ... createSvg('src/renderer/assets/icons/svg/') ], // ... }) module.exports = config
4、shims-vue.d.ts 文件加上
declare module "*.svg" { const content: any; // @ts-ignore export default content; }
5、main.ts文件中注册成全局组件
import { createApp } from 'vue' import App from './App.vue' import svgIcon from './components/SvgIcon.vue' // ... const app = createApp(App) app.component('SvgIcon', svgIcon) // ...
使用
直接在name中使用文件名
<svg-icon name="close" color="red"/>