vue3 + vite / webpack + ts 使用svg

在 webpack 中加载 svg 资源可以使用 svg-sprite-loader,而 vite 中可以使用插件 vite-plugin-svg-icons

vite中使用

安装vite-plugin-svg-icons

npm install vite-plugin-svg-icons
// 或
yarn add vite-plugin-svg-icons

配置vite

在vite.config.ts中配置插件
import {createSvgIconsPlugin} from 'vite-plugin-svg-icons'
...

 plugins: [
        ....
        createSvgIconsPlugin({
            // 要缓存的svg图标文件夹,需要识别的svg都应该放在这个文件夹内
            iconDirs: [path.resolve(__dirname, 'src/assets/svg-icon')],
            // 指定symbolId格式--> icon-name
            symbolId: 'icon-[name]'
        })
    ],

在这里插入图片描述

在main.ts中注册脚本
import 'virtual:svg-icons-register'

在components/svg-icon/下创建一个公共svg-icon.vue组件

// 组件 *components/svg-icon/index.vue* 完整代码如下:
<template>
  <svg
      class="svg-icon"
      :class="className"
      aria-hidden="true">
    <use :xlink:href="`#icon-${icon}`" :fill="color"/>
  </svg>
</template>

<script lang="ts" setup>

const props = defineProps({
  // SVG 图标名称L
  icon: {
    type: String,
    required: true
  },
  // 图标类名
  className: {
    type: String,
    default: ''
  },
  // svg颜色
  color: {
    type: String,
    default: '#000'
  }
})
</script>

<style scoped lang="scss">
.svg-icon {
  width: 1em;
  height: 1em;
  fill: currentColor;
  overflow: hidden;
}
</style>

在main.ts中注册全局组件
import SvgIcon from '@/components/svg-icon/index.vue'
...
app.component('svg-icon', SvgIcon)

在这里插入图片描述

使用
<template>
  <svg-icon icon="vue" className="start-page"></svg-icon>
</template>

<script lang="ts" setup>

</script>

<style scoped lang="less">
.start-page{
  width:300px;
  height: 210px;
  color: red;
}

</style>

在这里插入图片描述

注意如果需要修改svg颜色需要修改svg文件内容

在这里插入图片描述

在这里插入图片描述

webpack中使用

下载svg-sprite-loader插件

npm install svg-sprite-loader
配置vue.config中配置
const { defineConfig } = require('@vue/cli-service')
const path = require('path')
function resolve(dir) {
  return path.join(__dirname, dir)
}
module.exports = defineConfig({
  chainWebpack(config) {
    config.module.rule('svg').exclude.add(resolve('src/icons')).end()
    config.module
      .rule('icons')
      .test(/\.svg$/)
      .include.add(resolve('src/icons'))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]'
      })
      .end()
  }
})


在这里插入图片描述

剩余步骤同vite 。。。。
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值