Use rules

    1. Download SVG files
    1. The introduction of the file
    • import svg from '@/assets/icons/xx.svg'
    1. Install SVG – Sprite – loader
    • yarn add svg -sprite-loader -D
    1. Configuration shims – vue. Which s
       declare module "*.svg" {
           const content: string;
           export default content;
       } 
    Copy the code
    1. Configure the vue. Config. Js
    • userequireThis may cause ESLint to report an error. Depending on the node version you are using, you can use the import syntax instead
        const path = require('path')
      
        module.exports = {
            lintOnSave: false.chainWebpack: config= > {
                const dir = path.resolve(__dirname, 'src/assets/icons')
                
                config.module
                    .rule('svg-sprite')
                    .test(/\.(svg)(\? . *)? $/)
                    .include.add(dir).end() // Contains the ICONS directory
                    .use('svg-sprite-loader').loader('svg-sprite-loader').options({extract: false}).end()
                config.plugin('svg-sprite').use(require('svg-sprite-loader/plugin'), [{plainSprite: true}])
                config.module.rule('svg').exclude.add(dir) // Other SVG loaders exclude the ICONS directory}}Copy the code
    1. Use ICONS with SVG tags
        <svg>
            <use xlink:href="#xx" />
        </ svg>
    Copy the code

Importing SVG in batches

  • Importing the ICONS directory automatically imports all SVG files in the directory in batches
    • __WebpackModuleApi Eslint may report an error that is undefined, if it does, try declaring it at the top:

    /* global __WebpackModuleApi */

let importAll = (requireContext: __WebpackModuleApi.RequireContext) = >
  requireContext.keys().forEach(requireContext);
try {
  importAll(require.context(".. /assets/icons".true./\.svg$/));
} catch (error) {
  console.log(error);
}

Copy the code

Icon component encapsulation

  • Instead of verbose SVG tags
    // Icon.vue
    <template>
            <svg class="icon">
                <use :xlink:href="'#' + name" />
            </svg>
    </template>
    <script lang="ts">
        let importAll = (requireContext: __WebpackModuleApi.RequireContext) = >
          requireContext.keys().forEach(requireContext);
        try {
          importAll(require.context(".. /assets/icons".true./\.svg$/));
        } catch (error) {
          console.log(error);
        }
        export default {
            name: 'Icon'.props: ['name']}</script>
    <style lang="scss" scoped>
        .icon {
            width: 1em;
            height: 1em;
            vertical-align: -0.15 em;
            fill: currentColor;
            overflow: hidden;
        }
    </style>
Copy the code

Symbol style for IconFont document

.icon { 
    width: 1em; 
    height: 1em; 
    vertical-align: -0.15em; 
    fill: currentColor; 
    overflow: hidden; 
}
Copy the code