11.Vite项目如何全局封装 Svg 插件
一、使用 Svg 插件
- 安装 SVG 依赖插件
npm i vite-plugin-svg-icons -D
npm i fast-glob
- 在
vite.config.ts
中配置插件
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import vueDevTools from "vite-plugin-vue-devtools";
import { createSvgIconsPlugin } from "vite-plugin-svg-icons";
import path from "path";
export default defineConfig({
plugins: [
vue(),
vueDevTools(),
createSvgIconsPlugin({
iconDirs: [path.resolve(process.cwd(), "src/assets/icons")],
symbolId: "icon-[dir]-[name]",
}),
],
resolve: {
alias: {
"@": path.resolve("./src"),
},
},
server: {
port: "8080",
},
});
main.js
引入 svg 配置
import "virtual:svg-icons-register";
二、封装 svg 组件
- 新建
component/Svgicon/index.vue
<template>
<svg class="svg-icon" :class="className" aria-hidden="true">
<use :xlink:href="iconName" />
</svg>
</template>
<script setup>
import { defineProps, computed } from "vue";
const props = defineProps({
// icon 图标
icon: {
type: String,
required: true,
},
// 图标类名
className: {
type: String,
default: "",
},
});
const iconName = computed(() => `#icon-${props.icon}`);
</script>
<style scoped>
.svg-icon {
width: 100%;
height: 100%;
fill: currentColor;
overflow: hidden;
}
</style>
下载 Svg 存放在
src/assets/icons
目录下引入 Svgicon 组件
<script setup>
import SvgIcon from "../components/SvgIcon/index.vue";
</script>
<template>
<div class="wrapper">
<svg-icon icon="logo" />
</div>
</template>
<style lang="scss" scoped>
.wrapper {
width: 100%;
height: 100%;
}
.svg-container {
vertical-align: middle;
display: inline-block;
width: 80px;
height: 80px;
}
</style>
- 打开终端,执行
npm run dev
运行
npm run dev