"svg-sprite-loader": "^6.0.9", "svgo-loader": "^2.2.1",
npm i svgo-loader@2.2.1 npm install svg-sprite-loader -D
引入依赖使用
在components 中创建svgIcon插件
<template> <svg :class="svgClass" aria-hidden="true" v-on="$listeners"> <use :xlink:href="iconName" /> </svg></template><script>export default { name: "SvgIcon", props: { name: { type: String, required: true, }, className: { type: String, default: "", }, }, computed: { iconName() { return `#icon-${this.name}`; }, svgClass() { if (this.className) { return "scoped-svg-icon " + this.className; } else { return "scoped-svg-icon"; } }, },};</script><style lang="scss">.scoped-svg-icon { width: 1em; height: 1em; vertical-align: -0.15em; fill: currentColor; overflow: hidden;}</style>
然后床创建icons(名字自己定)
在icons中创建svg文件夹用来保存.svg文件
在icons中创建index.js
import Vue from "vue";import SvgIcon from "@/components/SvgIcon/index"; // 我创建的组件位置Vue.component("svg-icon", SvgIcon); // 注册组件const req = require.context("@/static/icons/svg/", false, /\.svg$/); //静态svg地址const requireAll = (requireContext) => requireContext.keys().map(requireContext);requireAll(req);
然后再在vue.config.js中配置
const { resolve } = require("path"); // resolve 使用path
chainWebpack: (config) => { config.module .rule("svg") .exclude.add(resolve("src/static/icons/svg")) .end(); config.module .rule("icons") .test(/\.svg$/) .include.add(resolve("src/static/icons/svg")) .end() .use("svg-sprite-loader") .loader("svg-sprite-loader") .options({ symbolId: "icon-[name]", }) .end() .before("svg-sprite-loader") .use("svgo-loader") .loader("svgo-loader") .options({ plugins: [{ removeAttrs: { attrs: "path:fill" } }], }) .end();
然后再在main.js中引用icons
import "./static/icons"; // 我保存的icons地址
然后使用
<svg-icon name="fire" className="svgIcon"></svg-icon> // svgIcon 图标的class