美文网首页
Webpack配置svg-sprite-loader处理svg图

Webpack配置svg-sprite-loader处理svg图

作者: key君 | 来源:发表于2019-10-16 16:42 被阅读0次

在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: {
    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 scoped>
.svg-icon {
  width: 1em;
  height: 1em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}
</style>

在src/icons/svg里添加svg文件
在src/icons新建index.js 全局定义svg组件

import Vue from 'vue';
import SvgIcon from '@/components/SvgIcon'

// 自动加载svg文件 
const req = require.context('./svg', false, /\.svg$/)
req.keys().map(req);

Vue.component('svg-icon', SvgIcon)

在main.js引入

import "@/icons";

npm run serve重启一下

使用

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

新建vue.config.js

const port = 7070;
const title = 'vue项目实践'//配置标题
const path = require('path')

function resolve(dir) {
    return path.join(__dirname, dir);
}

module.exports = {
    publicPath: '/best-practice',//配置url的路径
    devServer: {
        port
    },
    configureWebpack: {
        name: title
    },
    chainWebpack(config) {
        // 1.让svgloader排除掉src/icons这个目录
        config.module.rule('svg')
            .exclude.add(resolve('src/icons'));//以当前文件为起点 拼出src/icons的路径
        
        // 2.让插件svg-sprite-loader添加规则src/icons/svg
        config.module.rule('icons')
            .test(/\.svg$/)   //svg结尾的文件名
            .include.add(resolve('src/icons')).end()//include数组操作 end回退到上一层
            .use('svg-sprite-loader')
                .loader('svg-sprite-loader')
                .options({symbolId: 'icon-[name]'})
    }
}

npm run serve 更新端口信息
vue inspect>output.js 输出配置信息
npm i svg-sprite-loader 安装svg loader
vue inspect --rules 查看当前配置规则
vue inspect --rules svg 查看当前svg规则

相关文章

网友评论

      本文标题:Webpack配置svg-sprite-loader处理svg图

      本文链接:https://www.haomeiwen.com/subject/uwhumctx.html