vue3 vite和webpack环境下svg图标使用

631 阅读1分钟

vue3 vite和webpack环境下svg图标使用

背景

目前开发项目使用vue-cli创建的,但是由于项目越做越大,现在面临的问题是开发启动与打包越来越慢,所以在领导的建议下,开发环境转为vite开发,线上环境为了稳定继续保持webpack打包,基于以上前提,目前遇到一个问题,之前webpack环境下svg图标使用的svg-sprite-loader,但是在 Vite 项目下则行不通。

vite中可以使用vite-plugin-svg-icons插件引入svg,但是它需要在main.ts文件中加入import 'virtual:svg-icons-register',而这句话在webpack打包时会报错,报错如下:

1682664118500

解决

最终还是抛弃了vite-plugin-svg-icons这个插件,webpack环境下保持svg-sprite-loader不变,在vite环境下自定义一个svg引入插件来加载svg文件,

以达到和 svg-sprite-loader 的使用方式一样,这样就可以达到开发使用vite、打包使用webpack的目的了。

插件代码svg-loader.ts

import { readFileSync, readdirSync } from 'fs'
let idPerfix = ''
const svgTitle = /<svg([^>+].*?)>/
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) => {
                    let width = 0
                    let height = 0
                    let 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>')
            svgRes.push(svg)
        }
    }
    return svgRes
}
export const svgLoader = (path, perfix = 'icon') => {
    if (path === '') return
    idPerfix = perfix
    const res = findSvgFile(path)
    return {
        name: 'svg-transform',
        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>
        `
            )
        }
    }
}
使用

vite.config.ts(添加插件引用)

 plugins: [
        vue(), 
        svgLoader('./src/assets/icons/')
    ]

svg 公共组件

<template>
  <svg class="svg-icon" aria-hidden="true" :width="size + 'px'" :height="size + 'px'">
    <use :xlink:href="iconClass"></use>
  </svg>
</template><script lang="ts">
import { computed, defineComponent } from "vue";
​
export default defineComponent({
  name: "SvgIcon",
  isGlobal: true,
  props: {
    iconClass: {
      type: String,
      required: true,
    },
    size: {
      type: [String, Number],
      default: 20,
    },
  },
  setup(props) {
    const iconClass = computed(() => {
      return `#icon-${props.iconClass}`;
    });
​
    return {
      iconClass,
    };
  },
});
</script>

如果你也有webpack环境和vite环境同时使用的情况,可以参考本文章

扫码_搜索联合传播样式-标准色版.png