天天看点

vue3+vite+ts 通过svg-sprite-loader 插件使用自定义图标

第一步

首先下载svg插件和fs模块; 后续需要用到

npm install svg-sprite-loader -D
npm install fs
           

第二步新建文件夹和文件

vue3+vite+ts 通过svg-sprite-loader 插件使用自定义图标

将下载好的svg文件放入新建好的svg文件夹中

index.vue 代码 这里是创建一个

<svg-icon />

组件

<template>
  <svg :class="svgClass" v-bind="$attrs" :style="{ color: color }">
    <use :xlink:href="iconName" target="_blank" rel="external nofollow" ></use>
  </svg>
</template>
<script setup >
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>

           

index.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;
// 查找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;
}
// 生成svg
export const createSvg = (path: any, perfix = "icon") => {
  if (path === "") return;
  idPerfix = perfix;
  const res = svgFind(path);
  return {
    name: "svg-transform",
    transformIndexHtml(dom: String) {
      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>`
      );
    },
  };
};

           

第三步 打开main.ts 将创建好的

<svg-icon />

组件注入到全局组件

import { createApp } from "vue";
import svgIcon from "@/icons/index.vue";

const app = createApp(App);
app.component("svg-icon", svgIcon);
app.mount("#app");
           

第四步 在根目录打开vite.config.ts

import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import path from "path";

// 引入icons文件夹中的index.ts文件 
import { createSvg } from "./src/icons/index";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue(), createSvg("./src/icons/svg/")],
  resolve: {
    alias: {
      "@": path.resolve("./src"), // 相对路径别名配置,使用 @ 代替 src
    },
  }
  
});

           

**

注意

如果引入的文件爆红,“该目录不在项目的文件列表中,项目必须列出所有文件,或使用 “include” 模式。”

vue3+vite+ts 通过svg-sprite-loader 插件使用自定义图标

解决方案:打开根目录下的tsconfig.node.json文件的inclue中添加"src/icons/"

完整代码: “include”: [“vite.config.ts”, "src/icons/",]

vue3+vite+ts 通过svg-sprite-loader 插件使用自定义图标

**

最后使用

<svg-icon name="hamburger" width="20" height="20" />
           
vue3+vite+ts 通过svg-sprite-loader 插件使用自定义图标

引入成功

文章参考 原作者链接