Use SVG-Sprite-loader
Installation: Official documentation
npm install svg-sprite-loader -D
yarn add svg-sprite-loader -D
Copy the code
The official documentation tells us how to configure in webpack, but in vue-CLI it is a bit more troublesome, see the vue CLI documentation configuration file:
//vue.config.js const path = require('path') module.exports = { chainWebpack: config => { const dir = path.resolve(__dirname, 'SRC /assets/ ICONS ') config.module.rule (' svG-sprite ').test(/\.svg$/) //.include.add(dir).end() // the end of.svg contains only the ICONS directory .use('svg-sprite-loader').loader('svg-sprite-loader').options({extract: false}).end() .use('svgo-loader').loader('svgo-loader') .tap(options => ({... options, plugins: [{removeAttrs: {attrs: 'fill'}}]})).end() config.plugin('svg-sprite').use(require('svg-sprite-loader/plugin'), [{plainSprite: True}]) config.module.rule(' SVG ').exclude. Add (dir) // Other SVG loaders exclude ICONS directory}}Copy the code
Once configured, SVG can be imported as a symbol, which can then be used with the Use tag
2. Icon component
Importing SVG files one by one is too cumbersome. You can package an Icon component to import the Icon once and register it globally so that it can be easily used where needed.
However, the Icon component still needs to import SVG one by one. Can we import one directory at a time?
The answer is yes.
const importAll = (requireContext: __WebpackModuleApi.RequireContext) => requireContext.keys().forEach(requireContext); importAll(require.context('.. /assets/icons', true, /\.svg$/));Copy the code
In this way, all. SVG files in this directory are imported at once. Here is the encapsulated Icon component
<template> <svg class="icon"> <use :xlink:href="'#'+name"/> </svg> </template> <script lang="ts"> const importAll = (requireContext: __WebpackModuleApi.RequireContext) => requireContext.keys().forEach(requireContext); ImportAll (require.context('.. /assets/icons', true, /\.svg$/)); } catch (error) { console.log(error); } export default { name: "Icon", props: ['name'] }; </script>Copy the code
In this way, to use ICONS, you only need to pass in the ICON ID as the external attribute name of the icon component, and then to add new ICONS, you only need to place the file in the ICONS directory and use it directly.