1. Install svG-Sprite-loader

npm install svg-sprite-loader
Copy the code

2. Configure in vue.config.js

chainWebpack: config => {
    config.module
      .rule("svg")
      .exclude.add(path.join(__dirname, "src/assets/icon"))
      .end();
    config.module
      .rule("icon")
      .test(/\.svg$/)
      .include.add(path.join(__dirname), "src/assets/icon")
      .end()
      .use("svg-sprite-loader")
      .loader("svg-sprite-loader")
      .options({
        symbolId: "icon-[name]"
      })
      .end();
  }
Copy the code

3. Encapsulate svG-Icon components

<template> <svg class="svg-icon" aria-hidden="true"> <use :xlink:href="`#icon-${name}`" /> </svg> </template> <script> export default { props: { name: { type: String, required: true } } }; </script> <style> .svg-icon { width: 1em; height: 1em; Vertical - align: 0.15 em. fill: currentColor; overflow: hidden; } </style>Copy the code

use

<template> <SvgIcon name="account" /> <SvgIcon name="read" style="font-size: 20px; color: red" /> </template> <script> import SvgIcon from ".. /global/svgIcon"; import ".. /assets/icon/account.svg"; import ".. /assets/icon/read.svg"; export default { components: { SvgIcon }, } </script>Copy the code

To improve the

  • Each time a component is registered locally
  • Each use requires the introduction of a corresponding SVG
import SvgIcon from "./global/svgIcon.vue"; Const requireContext = require.context(// relative path of directory "./assets/icon", // whether to query subdirectory false, // Match the file's regular expression /\.svg$/); requireContext.keys().forEach(requireContext); // require.context() loads multiple resources. RequreiContext is the result of require.context(). CreateApp (App).use(Antd).use(store).use(router).component(" svG-icon ", SvgIcon) // global registration.mount ("# App ");Copy the code