vue3+vite svg图标的使用

这个基本纯属靠大佬,毕竟不会写插件这边就写写过程。

首先安装svg相应的开发插件

npm install svg-sprite-loader -D

 然后我们使用svg按照vue的开发文档上说都是先封装一个svg组件


 

 

然后我们要新建一个文件夹来保存我们包含对应图标的svg文件如

vue3+vite svg图标的使用_第1张图片

接下来就是插件,这个我不知道咋写,但是看到有大佬写了,这边分享一下(在这个插件的github上看到的,现在俺也找不到了)文件名svgBuilder.ts

import { Plugin } from 'vite'
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:any): string[] {
  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 = 0
          let height = 0
          let content = $2.replace(
            clearHeightWidth,
            (s1:string, s2:string, s3:number) => {
              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: string,perfix = 'icon'): Plugin => {
//   if (path === '') return
  idPerfix = perfix
  const res = findSvgFile(path)
  // console.log(res.length)
  // const res = []
  return {
    name: 'svg-transform',
    transformIndexHtml(html): string {
      return html.replace(
        '',
        `
          
            
              ${res.join('')}
            
        `
      )
    }
  }
}

 然后在vite.config.ts里面添加

export default defineConfig({
  plugins: [
    vue(),
    svgBuilder('./src/assets/icons/svg/'),
  ],
}

这个参数就是存放svg的文件夹所在的位置。

然后以后使用的时候像这样

就ok了

最后的效果

 

你可能感兴趣的:(vue3日常,vue.js,前端,es6)