前言
在使用 svg 图标的时候,建议使用 svg 雪碧图的方式加载 svg 图标。使用 svg-sprite-loader和 svgo-loader。这样就能想 iconfont 引入 svg 图标的方式进行使用了。
但是此时需要一个个地引入 svg 图标。而且不能用 import 引入,会在 webpack 打包的时候 treeshaking 掉,需要用 require 引入。
而且使用 svg 图标时候还要用 svg + use标签的方式使用,比较复杂。
常用的方式是封装一个 svg-icon (或者叫 svg-render)组件。自动批量加载 svg 图标。这样在使用的方式,直接组件➕图标name即可使用,简单方便。
svg-render 组件的封装方式如下,这里以 vue2 代码示例。
组件代码
<template><svg class="svg-icon" aria-hidden="true"><use :xlink:href="'#icon-' + name" /></svg></template><script>export default {name: "SvgIcon",props: {name: String,},};</script><style lang="scss" scoped>.svg-icon {width: 1em;height: 1em;fill: currentColor;overflow: hidden;}</style>
import SvgIcon from "./src/main.vue";SvgIcon.install = (Vue) => {const req = require.context("src/icons/svg", true, /\.svg$/);const importAll = (req) => req.keys().forEach(req);importAll(req);Vue.component(SvgIcon.name, SvgIcon);};export default SvgIcon;
webpack 配置
module: {rules: [{test: /\.svg$/,include: [path.resolve(__dirname, "src/icons/svg")],use: [{loader: "svg-sprite-loader",options: {symbolId: "icon-[name]"}},// {// loader: "svgo-loader",// options: {// plugins: [// {// name: "removeAttrs",// params: {// attrs: "fill"// }// }// ]// }// }]}]},
