第五十一章-vite插件-vite-plugin-svg-icon

1.说明

vite-plugin-svg-icons的npm首页

当你使用该插件的时候,指定好存放svg的文件夹。再按照指定的方式去访问svg图片。就可以再不产生http请求的情况下渲染出svg图片。

使用该插件时,插件会自动将所有svg图片加载到HTML中。并且每一个svg将会被过滤去无用的信息数据。让svg达到最小的值。之后使用svg图片就只需要操作DOM即可,而不需要发送http请求。

2.安装

yarn add vite-plugin-svg-icons --dev

3.创建配置

build\vite\plugin\svgSprite.ts

/**
 *  Vite Plugin for fast creating SVG sprites.
 * https://github.com/anncwb/vite-plugin-svg-icons
 */

import SvgIconsPlugin from 'vite-plugin-svg-icons';
import path from 'path';

export function configSvgIconsPlugin(isBuild: boolean) {
  const svgIconsPlugin = SvgIconsPlugin({
    // ↓本地svg图片地址
    iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],
    svgoOptions: isBuild,
    // 图标ID的样式
    symbolId: 'icon-[dir]-[name]',
  });
  return svgIconsPlugin;
}

选项svgOptionsboolean类型不太清楚是干什么的。但是对象类型是控制svg过滤无用信息的选项。使用true是使用默认选项,false时不知道做什么的但是也没什么影响。

4.用于配置

build\vite\plugin\index.ts

// ...
import { configSvgIconsPlugin } from './svgSprite';

export function createVitePlugins(viteEnv: ViteEnv, isBuild: boolean) {
  // ...
  // vite-plugin-svg-icons
  vitePlugins.push(configSvgIconsPlugin(isBuild));
  // ...
  return vitePlugins;
}

5.main导入

src\main.ts

// ...
import 'vite-plugin-svg-icons/register';
// ...

6.创建Svg组件

src\components\Icon\src\SvgIcon.vue

这里有一个样式,是全局上下文注入的。这个后面再讲,先写成string

<template>
  <svg class="vben-svg-icon" :class="[$attrs.class]" :style="getStyle" aria-hidden="true">
    <use :xlink:href="symbolId" />
  </svg>
</template>
<script lang="ts">
  import type { CSSProperties } from 'vue';
  import { defineComponent, computed } from 'vue';
  // import { useDesign } from '/@/hooks/web/useDesign';

  export default defineComponent({
    name: 'SvgIcon',
    props: {
      prefix: {
        type: String,
        default: 'icon',
      },
      name: {
        type: String,
        required: true,
      },
      size: {
        type: [Number, String],
        default: 16,
      },
    },
    setup(props) {
      // const { prefixCls } = useDesign('svg-icon');
      const symbolId = computed(() => `#${props.prefix}-${props.name}`);

      const getStyle = computed(
        (): CSSProperties => {
          const { size } = props;
          let s = `${size}`;
          s = `${s.replace('px', '')}px`;
          return {
            width: s,
            height: s,
          };
        }
      );
	  // prefixCls,
      return { symbolId, getStyle };
    },
  });
</script>
<style lang="less" scoped>
  // @prefix-cls: ~'@{namespace}-svg-icon';

  // .@{prefix-cls} {
  .vben-svg-icon {
    overflow: hidden;
    vertical-align: -0.15em;
    fill: currentColor;
  }
</style>

上一章

第五十章-Vben动态配置环境变量

下一章

第五十二章-Vite插件-vite-plugin-windicss

# vben  vite 

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×