在vue中使用svg-sprite-loader
第一步首先 npm install svg-sprite-loader --save
在assets文件夹下创建icons文件夹用来存放svg文件夹和index.js文件
index.js
import Vue from 'vue'
import SvgIcon from '@/components/SvgIcon'
// 注册全局组件
Vue.component('svg-icon', SvgIcon)
/**
* 固定语法 , webpack 上下文模块API 上下文模块导出一个带一个参数的(require)函数:
* 请求。导出的功能有3个属性:resolve,keys,id。
* resolve 是一个函数,返回已解析请求的模块ID。
* keys 是一个函数,它返回上下文模块可以处理的所有可能请求的数组
* */
const importAll = requireContext => requireContext.keys().map(requireContext)
/**
* require.context("./svg", false, /\.svg&/) 会去找 ./svg 文件夹下面的以 .svg结尾的所有文件
* 需要结合 importAll 使用
*
* require.context(directory, useSubdirectories, regExp)有三个参数:
* directory :说明需要检索的目录
useSubdirectories :是否检索子目录
regExp : 匹配文件的正则表达式
*/
const req = require.context('./svg', false, /\.svg$/)
importAll(req)
创建组件SvgIcon
<template>
<svg class="icon-svg" aria-hidden="true">
<use :xlink:href="IconName" />
</svg>
</template>
<script>
export default {
name: 'SvgIcon',
props: {
iconClass: {
default: '',
required: true
}
},
computed: {
// 用于接收传递的 svg 图标的名称
IconName() {
return `#icon-${this.iconClass}`
}
}
}
</script>
<style lang="scss" scoped>
// 导入的样式可以自定义
.icon-svg {
width: 1em;
height: 1em;
vertical-align: -0.15em;
fill: currentColor;
overflow: hidden;
}
</style>
在main.js中导入
import './assets/icons'
在vue.config.js中配置
const path = require('path')
function resolve(dir) {
return path.join(__dirname, dir)
}
module.exports = {
chainWebpack(config) {
config.plugins.delete('preload') // TODO: need test
config.plugins.delete('prefetch') // TODO: need test
// set svg-sprite-loader
config.module
.rule('svg')
.exclude.add(resolve('src/assets/icons'))
.end()
config.module
.rule('icons')
.test(/\.svg$/)
.include.add(resolve('src/assets/icons'))
.end()
.use('svg-sprite-loader')
.loader('svg-sprite-loader')
.options({
symbolId: 'icon-[name]'
})
.end()
}
}
最后使用方法
<svg-icon icon-class="此处为SVG文件名" />

浙公网安备 33010602011771号