Vite+Vue3.x环境下打包svg地图

实现:将 icons 文件夹下的 svg 图标打包到项目中、生成 svg 雪碧图,通过组件使用图标。

步骤:

1. 安装 vite-plugin-svg-icons

npm i vite-plugin-svg-icons -D

2. vite.config.ts 中的配置插件

import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import path from 'path'

export default defineConfig({
  plugins: [
    vue(),
    createSvgIconsPlugin({
      # 指定需要缓存的图标文件夹
      iconDirs: [path.resolve(process.cwd(), 'src/icons')],
      # 指定symbolId格式
      symbolId: 'icon-[dir]-[name]'
    })
  ]
})

3. 在 src/main.ts 内引入注册脚本

import 'virtual:svg-icons-register'

        到这里 svg 雪碧图已经生成

 4. 封装svg组件

         src / components / 新建 cp-icon.vue 组件

<script setup lang="ts">
defineProps<{
  name: string
}>()
</script>

<template>
  <svg aria-hidden="true" class="cp-icon">
    <!-- #icon-文件夹名称-图片名称 -->
    <use :href="`#icon-${name}`" />
  </svg>
</template>

<style lang="scss" scoped>
.cp-icon {
  // 和字体一样大
  width: 1em;
  height: 1em;
}
</style>

5. 配置 cp-icon 组件类型声明

        修改 src / types / components.d.ts 内容

import CpIcon from '@/components/cp-icon.vue'

declare module 'vue' {
  interface GlobalComponents {
    CpIcon: typeof CpIcon
  }
}

 

6. App.vue 中使用

<cp-icon name="home-article-active" />

 

End---------------------------

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值