之前的项目都是cli创建的,用webpack打包,今天自己写一个vite的demo的时候发现以前使用svg的配置用不了了,在网上查询了一下资料,现在整理了一份.
安装依赖
yarn add vite-plugin-svg-icons
或者
npm install vite-plugin-svg-icons
配置vite.config.js
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons';
import path from 'path';
export default defineConfig({
plugins: [
vue(),
createSvgIconsPlugin({
// 指定需要缓存的图标文件夹
iconDirs: [path.resolve(process.cwd(), 'src/assets/svg')],
// 指定symbolId格式
symbolId: 'icon-[dir]-[name]'
})
]
});
封装svg组件
<template>
<svg aria-hidden="true" class="svg-icon">
<use :xlink:href="symbolId" :fill="color" />
</svg>
</template>
<script>
import { defineComponent, computed } from 'vue';
export default defineComponent({
name: 'SvgIcon',
props: {
// 使用的svg图标名称,也就是svg文件名
name: {
type: String,
required: true
},
prefix: {
type: String,
default: 'icon'
},
color: {
type: String,
default: '#333'
}
},
setup(props) {
const symbolId = computed(() => `#${props.prefix}-${props.name}`);
return { symbolId };
}
});
</script>
<style scope>
.svg-icon {
width: 16px;
height: 16px;
color: #333;
fill: currentColor;
}
</style>
全局注册并使用
注册在main.js
import 'virtual:svg-icons-register';
import SvgIcon from '@/components/svg-icon/index.vue';
// 全局组件
const app = createApp(App);
// 将SvgIcon.vue组件注册为全局组件
app.component('SvgIcon', SvgIcon);
app.use(router).use(store).mount('#app');
在组件中使用,name就是你要使用的svg名称
<svg-icon class="add-icon" name="add"></svg-icon>