Vue项目引入Svg-sprite-loader插件

582 阅读1分钟

Vue项目引入Svg-sprite-loader插件

安装和配置 svg-sprite-loader:

1.安装

npm i -D svg-sprite-loader

2.webpack配置

配置路径地址: build -> webpack.base.conf.js

配置位置:module.exports -> module 中

{
        test: /\.svg$/,
        loader: 'svg-sprite-loader',
        include: [resolve('src/icons')],
        options: {
          symbolId: 'icon-[name]'
        }
      },
      {
        test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
        loader: 'url-loader',
        exclude: resolve('src/icons'),
        options: {
          limit: 10000,
          name: utils.assetsPath('img/[name].[hash:7].[ext]')
        }
      },

3.components 中新建组件 SvgIcon

> 路径:commponents -> 新建SvgIcon文件夹 -> index.vue
<template>
  <svg :class="svgClass" aria-hidden="true">
    <use :xlink:href="iconName"></use>
  </svg>
</template>

<script>
  export default {
    name: 'svg-icon',
    props: {
      iconClass: {
        type: String,
        required: true
      },
      className: {
        type: String
      }
    },
    computed: {
      iconName() {
        return `#icon-${this.iconClass}`
      },
      svgClass() {
        if (this.className) {
          return 'svg-icon ' + this.className
        } else {
          return 'svg-icon'
        }
      }
    }
  }
</script>

<style scoped>
  .svg-icon {
    width: 1.2em;
    height: 1.2em;
    vertical-align: -0.18em;
    fill: currentColor;
    overflow: hidden;
  }
</style>

4.创建Icons文件夹

页面路径:src -> 新建icons文件夹 ->同层创建index.js 和 svg文件夹(存放.svg格式图片)。

添加index.js内容

import Vue from 'vue'
import SvgIcon from '@/components/SvgIcon'// svg组件

// register globally
Vue.component('svg-icon', SvgIcon)

const requireAll = requireContext => requireContext.keys().map(requireContext)
const req = require.context('./svg', false, /\.svg$/)
requireAll(req)

5.入口 main.js 将 index.js 引入

import '@/icons'
然后 就可以使用了:

前面已经全局注册了,所以可以直接使用

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