webpack结合vue2.x使用svg

首先去阿里巴巴下载几张svg图片,然后新建iconfont文件夹用来存放svg相关,并新建index.js
在这里插入图片描述

index.js代码

// 引入 svg 目录下所有文件
const req = require.context('./svg', false, /\.svg$/)
const requireAll = requireContext => requireContext.keys().map(requireContext)
requireAll(req)

然后在components目录下新建svgIcon.vue

<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,
      default: ''
    }
  },
  computed: {
    iconName() {
      return `#icon-${this.name}`
    },
    svgClass() {
      if (this.name) {
        return 'svg-icon ' + this.name
      }
      return 'svg-icon'
    }
  }
}
</script>

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

由于我的项目是使用webpack搭建的,要修改一下webpack的配置

注意:如果你使用了url-loader来解析svg文件的话是不行的,要使用svg-sprite-loader,不然svg不会显示;命令:npm install svg-sprite-loader -D

安装完成后打开webpack.config.js来修改配置,这里只展示svg相关配置

			{
                test: /\.svg$/,
                include: [path.resolve('./src/assets/iconfont/svg')],
                use: {
                    loader: 'svg-sprite-loader',
                    options: {
                        symbolId: 'icon-[name]'
                    }
                }
                
            },
            {
                test: /\.(png|svg|jpg|gif|woff|ttf|webp|eot|woff2)$/,
                exclude: [path.resolve('./src/assets/iconfont/svg')],
                use: {
                    loader: 'url-loader',
                    options: {
                        limit: 3 * 1024,
                        outputPath: 'images', // 将文件打包到哪里
                        publicPath: 'images/',
                    }
                }
            },

在菜单组件引入svgIcon组件

menu.vue代码

components: {
    svgIcon(resolve) {
      require(["../components/svgIcon"], resolve)
    }
  },

在这里插入图片描述
路由文件里面的icon名称要和你svg里面的文件民对应起来
在这里插入图片描述

最后在main.js中引入iconfont文件夹下的index.js
在这里插入图片描述
在这里插入图片描述

如果项目是使用脚手架创建的,那么就要在vue.config.js配置

const path = require('path')
module.exports = {
	chainWebpack: config => {
         
        config.entry('main').add('babel-polyfill') // main是入口js文件
        // 其他配置
        config.module
        .rule('svg')
        .exclude.add(path.resolve(__dirname,"src/icons"))
        .end()
        config.module
        .rule('icons')
        .test(/\.svg$/)
        .include.add(path.resolve(__dirname,"src/icons"))
        .end()
        .use('svg-sprite-loader')
        .loader('svg-sprite-loader')
        .options({
            symbolId: 'icon-[name]'
        })
        .end()
    },
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值