Vite中使用vite-plugin-svg-icons插件
安装
// 安装插件
npm i vite-plugin-svg-icons -D
引入并配置插件
在vite.config.js中引入
...
import { resolve } from 'node:path'
// svg-icon插件
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
export default defineConfig(({command, mode})=>{
return {
// ...其他配置
plugins:[
// ...其他配置
createSvgIconsPlugin({
// 指定需要缓存的图标文件夹目录
iconDirs: [resolve(process.cwd(), 'src/assets/svgIcons')],
// 指定symbolId格式
symbolId: 'icon-[dir]-[name]',
//svgo额外配置,具体配置参考https://github.com/svg/svgo
svgoOptions: {
plugins: [
{
name: 'removeAttrs',
params: { attrs: ['class', 'data-name', 'fill', 'stroke'] }
}
]
}
})
]
}
})
创建SvgIcon组件
在src/components目录下创建SvgIcon组件,内容如下
template>
<svg :class="svgClass" aria-hidden="true">
<use :xlink:href="iconName" :fill="color" />
</svg>
</template>
<script setup>
const props = defineProps({
// icon名称
iconName: {
type: String,
required: true
},
//组件额外类名
className: {
type: String,
default: ''
},
// 颜色属性
color: {
type: String,
default: ''
}
})
const iconName = computed(() => `#icon-${props.iconClass}`)
const svgClass = computed(() => `svg-icon ${props.className}`)
</script>
<style lang="scss" scoped>
.svg-icon {
width: 1em;
height: 1em;
position: relative;
fill: currentColor;
vertical-align: -2px;
}
</style>
全局引入并注册SvgIcon组件
在main.js中引入并全局注册
import SvgIcon from '@/components/SvgIcon'
// ...其他
app.component('svg-icon', SvgIcon)
使用SvgIcon组件
<svg-icon class-name="icon-config" icon-class="config"></svg-icon>
//...
<style>
.icon-config{
font-size:20px;
color:#000
}
</style>
本文介绍了如何在Vite项目中使用vite-plugin-svg-icons插件来管理和使用SVG图标,详细步骤包括插件的安装、配置、创建SvgIcon组件、全局引入和注册,以及组件的使用方法。
1670

被折叠的 条评论
为什么被折叠?



