一、安装SVG依赖插件
pnpm install vite-plugin-svg-icons -D
二、在vite.config.ts
中配置插件
// vite.config.ts
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import path from 'path'
export default () => {
return {
plugins: [
createSvgIconsPlugin({
// 指定要缓存.svg文件的文件夹
iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],
// Specify symbolId format
symbolId: 'icon-[dir]-[name]',
}),
],
}
}
三、入口文件(main.ts)导入
// main.ts
import 'virtual:svg-icons-register'
四、封装SvgIcon组件
参考路径:src\components\SvgIcon.vue
<!-- src\components\SvgIcon.vue -->
<script lang="ts" setup>
defineProps({
//xlink:href属性值的前缀
prefix: {
type: String,
default: '#icon-',
},
//svg矢量图的名字
name: String,
//svg图标的颜色
color: {
type: String,
default: '',
},
//svg宽度
width: {
type: String,
default: '16px',
},
//svg高度
height: {
type: String,
default: '16px',
},
})
</script>
<template>
<div>
<svg :style="{ width, height }">
<use :xlink:href="prefix + name" :fill="color"></use>
</svg>
</div>
</template>
五、组件注册
5.1 局部注册
在组建中直接导入使用:
import svgIcon from '@/components/SvgIcon.vue'
5.2 全局注册
在main.ts中导入全局注册
// main.ts
import SvgIcon from '@/components/SvgIcon.vue'
app.component('SvgIcon', SvgIcon)
5.3 利用自定义插件注册所有全局组件
在src文件夹目录下创建一个index.ts文件:用于注册components文件夹内部全部全局组件
路径src/components/index.ts
// src/components/index.ts
import SvgIcon from './SvgIcon.vue';
import type { App, Component } from 'vue';
const components: { [name: string]: Component } = { SvgIcon };
export default {
install(app: App) {
Object.keys(components).forEach((key: string) => {
app.component(key, components[key]);
})
}
}
在入口文件(main.ts)引入src/index.ts文件,通过app.use方法安装自定义插件
// main.ts
import gloablComponent from './components/index';
app.use(gloablComponent);
六、说明
1、本博客中的文章摘自网上的众多博客,仅作为自己知识的补充和整理,并分享给其他需要的 coder,不会用于商用;
2、因为很多博客的地址已经记不清楚了,所以不会在这里标明出处;
3、参考配置:vue3 + ts + vite