素材巴巴 > 程序开发 >

vite vue3项目中使用SVG

程序开发 2023-09-18 06:48:46

在开发过程中发现在vite+vue3项目中与在vue2项目中使用SVG的方式有所区别。下面将详细操作记录下来。

首先我们先来看一下项目目录。

stept1:安装svg-sprite-loader

yarn add svg-sprite-loader -D

stept2:在components目录下创建SvgIcon.vue文件

stept3:在src目录下创建icons目录,用来存放SVG文件

 

stept4:在main.js中将我们的SvgIcon组件全局注册

 

stept5:在src下新建plugins文件夹,创建svgBuilder.js

import { readFileSync, readdirSync } from "fs"
 ​
 let idPerfix = ""
 const svgTitle = /+].*?)>/
 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) => {// console.log(++i)// console.log(dirent.name)let width = 0let height = 0let 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 ``}).replace("", "")svgRes.push(svg)}}return svgRes
 }
 ​
 export const svgBuilder = (path, perfix = "icon") => {if (path === "") returnidPerfix = perfixconst res = findSvgFile(path)// console.log(res.length)// const res = []return {name: "svg-transform",transformIndexHtml(html) {return html.replace("",`${res.join("")}`)}}
 }

stept6: 在vite.config.js修改配置

 

stept7: 在项目中使用,name和color必传

 

完活!

 


标签:

上一篇: 学习OA系统制作历程day1 下一篇:
素材巴巴 Copyright © 2013-2021 http://www.sucaibaba.com/. Some Rights Reserved. 备案号:备案中。