vue3 + vite svg-icon配置

文章介绍了如何在Vue项目中通过svg-sprite-loader处理SVG图标,创建了一个名为svgIcon的组件,将SVG图标存放在icons文件夹,然后在main.js中全局注册该组件。此外,还展示了在plugins中创建svgBuilder.js脚本,自动处理SVG文件并整合到Vite配置中,以便于管理和使用SVG图标。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.文件目录

2.安装 svg-sprite-loader

npm install svg-sprite-loader -D
# via yarn
yarn add svg-sprite-loader -D

3.创建svgIcon.vue文件

   <template>
  <svg :class="svgClass" v-bind="$attrs" :style="{color: color}">
    <use :xlink:href="iconName"/>
  </svg>
</template>

<script setup>


import { defineProps, computed } from "vue";

const props = defineProps({
  name: {
      type: String,
      required: true
    },
    color: {
      type: String,
      default: ''
    }
})

const iconName = computed(()=>`#icon-${props.name}`);
const svgClass = computed(()=> {
  console.log(props.name, 'props.name');
  if (props.name) {
        return `svg-icon icon-${props.name}`
      }
      return 'svg-icon'
});
</script>

<style lang='scss'>
.svg-icon {
  width: 1em;
  height: 1em;
  fill: currentColor;
  vertical-align: middle;
}
</style>

4.创建icons文件夹,存放svg文件

5.在main.js里面全局注入svg-icon组件

import { createApp } from 'vue'
import App from './App.vue'

import svgIcon from './components/svgIcon.vue'

createApp(App).component('svg-icon', svgIcon).mount('#app');

6.在plugins文件夹创建svgBuilder.js

import { readFileSync, readdirSync } from 'fs'

let idPerfix = ''
const svgTitle = /<svg([^>+].*?)>/
const clearHeightWidth = /(width|height)="([^>+].*?)"/g

const hasViewBox = /(viewBox="[^>+].*?")/g

const clearReturn = /(\r)|(\n)/g

function findSvgFile(dir) {
  const svgRes = []
  const dirents = readdirSync(dir, {
    withFileTypes: true
  })
  for (const dirent of dirents) {
    if (dirent.isDirectory()) {
      svgRes.push(...findSvgFile(dir + dirent.name + '/'))
    } else {
      const svg = readFileSync(dir + dirent.name)
        .toString()
        .replace(clearReturn, '')
        .replace(svgTitle, ($1, $2) => {
          // console.log(++i)
          // console.log(dirent.name)
          let width = 0
          let height = 0
          let content = $2.replace(
            clearHeightWidth,
            (s1, s2, s3) => {
              if (s2 === 'width') {
                width = s3
              } else if (s2 === 'height') {
                height = s3
              }
              return ''
            }
          )
          if (!hasViewBox.test($2)) {
            content += `viewBox="0 0 ${width} ${height}"`
          }
          return `<symbol id="${idPerfix}-${dirent.name.replace(
            '.svg',
            ''
          )}" ${content}>`
        })
        .replace('</svg>', '</symbol>')
      svgRes.push(svg)
    }
  }
  return svgRes
}

export const svgBuilder = (path, perfix = 'icon') => {
  if (path === '') return
  idPerfix = perfix
  const res = findSvgFile(path)
  // console.log(res.length)
  // const res = []
  return {
    name: 'svg-transform',
    transformIndexHtml(html) {
      return html.replace(
        '<body>',
        `
          <body>
            <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="position: absolute; width: 0; height: 0">
              ${res.join('')}
            </svg>
        `
      )
    }
  }
}

7.最后在vite.config.js修改配置

import { svgBuilder } from './src/plugins/svgBuilder'; 

export default defineConfig({
  plugins: [svgBuilder('./src/icons/svg/')] // 这里已经将src/icons/svg/下的svg全部导入,无需再单独导入
})

### 配置和使用 SVG 图标的步骤 #### 插件安装 为了在 Vue 3Vite 构建工具中高效地处理 SVG 图标,推荐使用 `vite-plugin-svg-icons` 这个插件。通过此插件可以在项目启动时预加载所有图标,并且只会在文件发生更改的情况下重新生成这些图标,从而提高性能。 对于包管理器的选择有 Yarn、NPM 或 Pnpm: - 使用 Yarn 的命令为 `yarn add vite-plugin-svg-icons -D` - 对于 NPM 用户,则应执行 `npm install vite-plugin-svg-icons -D` - 如果偏好 Pnpm,那么相应的指令是 `pnpm install vite-plugin-svg-icons -D`[^1][^2]. #### 配置 Vite 完成上述依赖项的添加之后,在项目的根目录下找到或创建名为 `vite.config.ts` 文件用于配置 Vite 设置。在此处引入并注册 `createSvgIconsPlugin()` 函数作为插件的一部分,以便能够自定义路径以及指定要缓存哪些图标集。 ```typescript import { defineConfig } from &#39;vite&#39; import vue from &#39;@vitejs/plugin-vue&#39; import path from &#39;path&#39; import { createSvgIconsPlugin } from &#39;vite-plugin-svg-icons&#39; export default defineConfig({ plugins: [ vue(), createSvgIconsPlugin({ iconDirs: [path.resolve(process.cwd(), &#39;src/icons&#39;)], symbolId: &#39;icon-[dir]-[name]&#39; }) ] }) ``` 这段代码片段展示了如何设置图标所在的相对路径 (`src/icons`) 并指定了每个图标的唯一 ID 模式. #### 组件内引用 为了让组件可以直接访问已导入的 SVG 资源而不必单独 import 每张图片,可以通过全局方式注入 `<symbol>` 标签至 HTML 文档头部。这一步骤通常是在应用入口文件 (如 main.js/main.ts) 中实现: ```javascript // 自动注册所有 .svg?inline 结尾的模块为 Web Components app.component(&#39;component-name&#39;, { render() { return this.$slots.default?.()[0]; } }); ``` 实际上,由于采用了 `vite-plugin-svg-icons` 提供的功能,开发者只需要确保所需图标存在于之前设定好的 icons 文件夹里即可自动生效. #### 实际案例展示 假设有一个按钮需要显示购物车图标,此时无需手动编写复杂的模板语句;相反,只需简单地利用已经准备完毕的符号名称来调用它: ```html <template> <button class="cart-button"> <!-- 假设 shopping-cart.svg 存在于 src/icons/ 目录 --> <svg><use xlink:href="#icon-shopping-cart"/></svg> Add to Cart </button> </template> <style scoped> .cart-button svg { width: 24px; height: 24px; } </style> ``` 这样不仅简化了开发流程还提高了可维护性和一致性[^3].
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值