Vue3 + vite svg 組件

Vue3 + vite 編寫svg組件,本質上和vue2 + webpack 沒有多大出入,唯一不同的是得編寫一個vite插件

WbIcon.vue

這個文件和之前沒多大改變,不一樣之處是用了setup,可以按需更改,當然了不改也能食用。

<template>
    <svg :class="svgClass" aria-hidden="true" v-bind="$attrs">
        <use :xlink:href="iconName" />
    </svg>
</template>

<script setup>
import { computed, defineProps } from 'vue';
const props = defineProps({
    name: {
        type: String,
        required: true,
    }
})

const iconName = computed(() => `#icon-${props.name}`);

const svgClass = computed(() => {
    if (props.name) {
        return `wb-icon svg icon-${props.name}`
    }
    return 'wb-icon svg'
})
</script>

<style lang="scss" scoped>
.wb-icon.svg {
    width: 1em;
    height: 1em;
    fill: currentColor;
    overflow: hidden;
    vertical-align: middle;
}
</style>

在main.js中引入WbIcon組件

網上有好多文章,沒說明引入,我這提一下

import { createApp } from "vue";
import router from "./router";
import App from "./App.vue";
import WbIcon from "@/components/icon/WbIcon.vue";

import "@/assets/css/index.scss";

const app = createApp(App);
app.component("WbIcon", WbIcon);

app.use(router).mount("#app");

新建如下目錄,補全文件

assets
├── icon
│   ├── svg // 下存儲svg文件
│   │   └── analysis-icon.svg
│   └── svgBuilder.js // vite 插件主要是為了loader svg

svgBuilder.js

這個文件是從網上直接copy的,他們寫是ts版本的,我這刪掉類型聲明那些東西,改成了js版本的

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 svgBuilder = (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.js內補全插件

做完以上這些,在vite.config.js添加plugin即可

import { defineConfig } from "vite";
import { svgBuilder } from "./src/assets/icon/svgBuilder";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    ...
    svgBuilder("./src/assets/icon/svg/")],
});

最終效果

  • 使用

    <template>
      <wb-icon name="analysis-icon" style="color:aqua; margin: 200px;font-size: 2em;"></wb-icon>
    </template>
    
  • 效果


    最終效果加載失敗
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容