vite svg 插件

vite2 vue3 加载svg 图片

import { readFileSync, readdirSync } from 'fs'
const path = require('path')

const svgTitle = /<svg([^>+].*?)>/
const clearHeightWidth = /(width|height)="([^>+].*?)"/g

const hasViewBox = /(viewBox="[^>+].*?")/g

const clearReturn = /(\r)|(\n)/g

/**
 * @Date 2021/11/22
 * @Author Varus
 * @Description: 找到svg 图片并且替换文件信息
 * @param dir svg 目录
 * @param idPreFix svg symbol id
 *
 */
function findSvgFile(dir, idPreFix) {
    const svgRes = []
    const dirEntries = readdirSync(dir, {
        withFileTypes: true
    })
    for (const dirent of dirEntries) {
        if (dirent.isDirectory()) {
            svgRes.push(...findSvgFile(path.join(dir, dirent.name)))
        } else {
            const svg = readFileSync(path.join(dir, dirent.name))
                .toString()
                .replace(clearReturn, '')
                .replace(svgTitle, ($1, $2) => {
                    let width = 0
                    let height = 0
                    let content = $2.replace(
                        clearHeightWidth,
                        (s1, s2, s3) => {
                            s3 = s3.replace('px', '')
                            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="${idPreFix}-${dirent.name.replace(
                        '.svg',
                        ''
                    )}" ${content}>`
                })
                .replace('</svg>', '</symbol>')
            svgRes.push(svg)
        }
    }
    return svgRes
}

/**
 * @Date 2021/11/18
 * @Author Varus
 * @Description: 加载svg 文件
 *
 */
export default function (path, prefix = 'icon') {
    if (path === '') return
    const res = findSvgFile(path, prefix)
    // console.log(res)
    return {
        name: 'svg-transform',
        // vite 插件 直接替换 html 页签内容
        transformIndexHtml(html) {
            return html.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 vue from '@vitejs/plugin-vue'
import svgLoader from './src/plugins/svg-loader'
const path = require('path')


function resolve (dir) {
  return path.join(__dirname, dir)
}
const setting = require('./src/setting.js')

export default defineConfig({
  resolve: {
    alias:{
      '@': path.resolve(__dirname, "src")
    },
  },
  server: {
    fs: {
      strict: false
    },
  },
  plugins: [vue(), svgLoader(resolve('src/icons/svg/'))]
})

引用以下以下问题ISSUE
相关的git :https://github.com/JetBrains/svg-sprite-loader/issues/434

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值