“This is the third day of my participation in the First Challenge 2022, for more details: First Challenge 2022”.

There are many SVG images in the project, and we started the project by importing SVG ICONS as VUE components using the vuE-SVG-Loader recommended by Ant-Design-Vue. There are two problems in using VUE-SVG-loader:

  1. Pictures to use, first to import, and then to use;
  2. Different SVG images have id conflicts and style changes after compilation.

Today I learned and used SVG-Sprite-loader. The SVG-Sprite-loader does not have ID conflicts for SVG images, and does not need to display imported SVG images when using it, greatly improving the development efficiency.

The procedure for configuring and using SVG-sprite-loader is as follows:

Install SVG – Sprite – loader

npm i svg-sprite-loader -D
Copy the code

Configure the vue. Config. Js

chainWebpack: (config) = > {
    const svgRule = config.module.rule("svg");
    // Clear the default SVG rules
    svgRule.uses.clear();
    // Add an SVG-sprite-loader rule for SVG files
    svgRule
      .test(/\.svg$/)
      .use("svg-sprite-loader")
      .loader("svg-sprite-loader")
      .options({
        symbolId: "icon-[name]"}); },Copy the code

Create the SvgIcon/ index.vue component in the Components directory

<template>
  <svg :class="svgClass" aria-hidden="true">
    <use :xlink:href="iconName" />
  </svg>
</template>

<script>
export default {
  name: "SvgIcon".props: {
    iconClass: {
      type: String.required: true,},className: {
      type: String,}},computed: {
    iconName() {
      return `#icon-The ${this.iconClass}`;
    },
    svgClass() {
      if (this.className) {
        return "svg-icon " + this.className;
      } else {
        return "svg-icon"; ,}}}};</script>

<style scoped>
.svg-icon {
  width: 1em;
  height: 1em;
  vertical-align: -0.15 em;
  fill: currentColor;
  overflow: hidden;
}
</style>

Copy the code

Globally register SVG components

In the ICONS directory, create an SVG directory and an index.js file respectively. The SVG directory stores. SVG files.

import Vue from "vue";
import SvgIcon from ".. /components/SvgIcon/Index"; / / SVG components
// Globally register components
Vue.component("svg-icon", SvgIcon);
// Define a function to load a directory
const requireAll = (r) = > r.keys().map(r);
// Load all SVG files in the directory
requireAll(require.context("./svg".false./\.svg$/));
Copy the code

Import the ICONS file in the main.js project entry file

use

//icon-class: specifies the name of the SVG image
//class-name: SVG image style class name
<svg-icon icon-class="time" class-name="icon" />
Copy the code