1、通过插件动态导入svg文件
安装vite插件vite-plugin-svg-icons
npm i vite-plugin-svg-icons -D
配置插件svg-icon.ts
import { createSvgIconsPlugin } from "vite-plugin-svg-icons";
import path from "path";export default function createSvgIcon(isBuild: boolean) {return createSvgIconsPlugin({iconDirs: [path.resolve(process.cwd(), "src/assets/icons/svg")],symbolId: "icon-[dir]-[name]",svgoOptions: isBuild,});
}
vite导入插件vite.config.ts
export default defineConfig(({ command, mode }) => {const env = loadEnv(mode, process.cwd());const { VITE_APP_ENV } = env;const config = command === "build" ? buildConfig : serveConfig;return {plugins: [vue(), createSvgIcon(command === "build")],resolve: {alias: {"@": fileURLToPath(new URL("./src", import.meta.url)),},},...config,};
});
main.ts引入svg文件
import "virtual:svg-icons-register";
2、将svg批量生成为vue组件
本例子以element plus为例,将svg生成为element plus icon 对应的svg component
svg组件(svgIcon.vue)
<template><svg viewBox="0 0 1024 1024"><use :xlink:href="iconName" /></svg>
</template><script lang="ts" name="CompSvgIcon" setup>
import { computed } from "vue";const props = withDefaults(defineProps<{iconClass: string;}>(),{}
);const iconName = computed(() => `#icon-${props.iconClass}`);
</script><style scope lang="less"></style>
批量生成svg组件(myIcon.ts)
import { defineComponent, h } from "vue";
import svgIcon from "./index.vue";
const modules = import.meta.glob("./../../assets/icons/svg/*.svg");// 获取icon名称
const filenNmes = [];
for (const path in modules) {const name = path.split("assets/icons/svg/")[1].split(".svg");filenNmes.push(name[0]);
}/*** icons组件名称数组 (my + Filename)*/
export const myIconNames = filenNmes.map((name) => "my" + name.replace(/^./, (L) => L.toUpperCase()));/*** icons组件数组*/
const myIcons = filenNmes.map((name) => {return {name: "my" + name.replace(/^./, (L) => L.toUpperCase()),component: defineComponent({render() {return h(svgIcon, { iconClass: name });},}),};
});export default myIcons;
main.ts文件中引入
import myIcons from "@/components/SvgIcon/myIcon";const app = createApp(App);
myIcons.forEach((item) => {app.component(item.name, item.component);
});
使用自定义svg组件同el icon一致,icon组件名称为(my + Filename),名称可以myIcon.ts自行修改
<el-icon><my404 />
</el-icon>
效果
3、源码地址
vue3+element plus+ts::https://gitee.com/huanglgln/vue-sys-manage-el