2026-week-8st

5 阅读1分钟

svg-icon 统一封装使用

import { createSvgIconsPlugin } from "vite-plugin-svg-icons";

export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd(), "");
  return {
    base: env.VITE_STATIC_URL,
    publicDir: "public",
    server: {
    },
    plugins: [
      vue(),
      AutoImport({
        resolvers: [ArcoResolver()]
      }),
      Components({
        resolvers: [
          ArcoResolver({
            sideEffect: true
          })
        ]
      }),
      createSvgIconsPlugin({
        iconDirs: [path.resolve(process.cwd(), "src/assets/icons")], //icon 本地存储路径
        symbolId: "icon-[dir]-[name]", //使用方式 icon 本地存储路径>文件夹>svg图标名称
        //<svg-icon icon-class="warn-workbench-export" /> 
        inject: "body-last",
        customDomId: "__svg__icons__dom__"
      }),
    ],
    build: { target: "es2015" }
  };
});

公共方法、组件全局引入

import confirmCustom from "@/components/confirm-modal/index.js";
import confirmCustomErr from "@/components/confirm-modal-err/index.js";
import { Message, Modal } from "@arco-design/web-vue";
import Dayjs from "dayjs";
import { debounce, throttle } from "lodash";

Modal.confirmCustom = confirmCustom;
Modal.confirmCustomErr = confirmCustomErr;

class PluginInstall {
  constructor() {
    this.install = (app) => { // 注意这里的install ,其实 app.use(xxx),也是去找xxx里面的install 方法,所以这里可以全局注册公共方法或者组件!!!
      this.initPlugin(app);
    };
    this.initPlugin = (app) => {
      app.provide("$message", Message);
      app.provide("$confirm", Modal);
      app.provide("dayjs", Dayjs);
      app.provide("lodash", this.getLodash());
    };
    this.getLodash = () => {
      return { throttle, debounce };
    };
  }
}

const pluginInstall = new PluginInstall();
export default pluginInstall;

import pluginInstall from "./utils/plugin-install";

const app = createApp(App);
app
  .use(pluginInstall)
  .mount("#app");

全局导入 主要还是借助.install()

import VueEcharts from "vue-echarts";
import SvgIcon from "./SvgIcon/index.vue";
import AsyncComponent from "./async-component/index.vue";
import CustomEmpty from "@/components/custom-empty/index.vue";

export default {
  install(app) {
    app.component("svg-icon", SvgIcon);
    app.component("async-component", AsyncComponent);
    app.component("vue-chart", VueEcharts);
    app.component("custom-empty", CustomEmpty);
  }
};

import globalComponents from "@/components";

const app = createApp(App);
app
  .use(globalComponents)
  .mount("#app");