- 预加载 在项目运行时就生成所有图标
- 高性能 内置缓存,仅当文件被修改时才会重新生成
安装依赖
// yarn 安装
yarn add vite-plugin-svg-icons
// npm 安装
npm i vite-plugin-svg-icons
配置
在 vite.config.ts 中配置插件
import { createSvgIconsPlugin } from "vite-plugin-svg-icons";
export default defineConfig({
plugins: [
vue(),
createSvgIconsPlugin({
// src/assets/img/sv 是存放 svg 图片的目录
iconDirs: [path.resolve(process.cwd(), "src/assets/img/svg")],
symbolId: "icon-[name]",
}),
],
});
注册
在 main.ts 中注册
import "virtual:svg-icons-register";
使用及封装
1,封装
在 components 文件夹中创建 svgIcon.vue 文件
<script>
import { defineComponent, computed } from "vue";
export default defineComponent({
/**
* name svg 图片名称
* color 图片颜色
* className 自定义样式
*/
props: {
name: {
type: String,
required: true,
},
color: {
type: String,
default: "",
},
className: {
type: String,
default: "",
},
},
setup(props) {
return {
svgClass: computed(() => {
if (props.className) {
return `svg-icon ${props.className}`;
}
return "svg-icon";
}),
};
},
});
</script>
<template>
<svg aria-hidden="true" :class="svgClass">
<use :href="`#icon-${name}`" :fill="color" />
</svg>
</template>
<style lang="scss" scoped>
.sub-el-icon,
.nav-icon {
display: inline-block;
font-size: 15px;
margin-right: 12px;
position: relative;
}
.svg-icon {
width: 1em;
height: 1em;
position: relative;
fill: currentColor;
vertical-align: -2px;
}
</style>
2,使用
import SvgIcon from "@/components/svgIcon.vue";
<SvgIcon :name="form" />
3,报错及修复
安装一下依赖就好了
npm i fast-glob