vue项目中配置svg图标 cli3路径

1 添加依赖

npm install svg-sprite-loader file-loader -D

2 在components目录下新增一个IconSvg.vue文件

<template>
  <svg class="svg-icon" aria-hidden="true" v-on="$listeners">
    <use :xlink:href="iconName" />
  </svg>
</template>
 
<script>
export default {
  name: "icon-svg",
  props: {
    iconClass: {
      type: String,
      required: true
    },
    className: {
      type: String,
      default: ""
    }
  },
  computed: {
    iconName() {
      return `#icon-${this.iconClass}`;
    },
    svgClass() {
      if (this.className) {
        return "svg-icon " + this.className;
      } else {
        return "svg-icon";
      }
    }
  }
};
</script>
 
<style>
.svg-icon {
  /* 
  这里可以自定义宽高
   1em;
  height: 1em; 
  */
   2em;
  height: 2em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}
</style>

3、添加icon-svg组件

  在main.js中 新增全局组件

   //引入svg组件
   import IconSvg from './components/IconSvg'

   // //全局注册icon-svg
   Vue.component('icon-svg', IconSvg)


4、配置vue.config.js

const path = require('path')
module.exports = {
  /**这里之后,还有第一行的path是跟svg有关系的配置**/
  chainWebpack: config => {
    const svgRule = config.module.rule('svg')
    // 清除已有的所有 loader。
    // 如果你不这样做,接下来的 loader 会附加在该规则现有的 loader 之后。
    svgRule.uses.clear()
    svgRule
      .test(/.svg$/)
      // 配置icons的目录  我这里默认放在了 /src/assets/icons 目录下  如要修改 记得更换你的目录
      .include.add(path.resolve(__dirname, './src/assets/icons'))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]'
      })
    const fileRule = config.module.rule('file')
    fileRule.uses.clear()
    fileRule
      .test(/.svg$/)
      // 配置icons的目录  我这里默认放在了 /src/assets/icons 目录下  如要修改 记得更换你的目录
      .exclude.add(path.resolve(__dirname, './src/assets/icons'))
      .end()
      .use('file-loader')
      .loader('file-loader')
  }
}

5、使用方式

   导入.svg图标

  import "@/assets/icons/aa.svg"

  使用图标

  <icon-svg icon-class="aa" />





原文地址:https://www.cnblogs.com/stevenzhangcy/p/12979185.html