问题:我们在项目开发的时候,是分阶段的开发,不可能一次性就将整个项目需要的icon图标都准备好,所有会分批次导入项目,这就很麻烦,每次新增icon图标都会重新导入一遍图标文件。我就想能不能实现不多次导入图标依赖文件,只需要导入我们所需要的图标文件。
然后我就发现可以使用svg格式的方式,不在使用class格式。
以后你想新增icon,直接向里面增加svg文件就行,如果你还想降低用户的操作难度,可以,在这个基础上让后端配合你写个接口,调用这个接口,就可以在服务器上你指定的文件下生成一个svg文件,当然这样的话,你的src/assets/icons/svg文件就不能参与压缩了,你的保留它,在压缩的时候。
当然,也可以使用线上图标引入方式。
svg格式:
1、安装依赖
npm install svg-sprite-loader --save-dev
安装完依赖之后,这里之后打包的时候,可能会报非常多错误,比如:Error Cannot find module ‘webpacklibRuleSet‘
若有报这个错误,重新安装一下webpack
npm i webpack@4.29.5 --force
2、所有svg图标放到src/assets/icons/svg文件夹下,并在src/assets/icons下创建文件index.js
index.js
const req = require.context('./svg', false, /\.svg$/)
const requireAll = requireContext => requireContext.keys().map(requireContext)
requireAll(req)
3、vue.config.js文件中配置
const path = require('path');
module.exports = {
chainWebpack: config => {
// svg rule loader
const svgRule = config.module.rule('svg') // 找到svg-loader
svgRule.uses.clear() // 清除已有的loader, 如果不这样做会添加在此loader之后
svgRule.exclude.add(/node_modules/) // 正则匹配排除node_modules目录
svgRule // 添加svg新的loader处理
.test(/\.svg$/)
.use('svg-sprite-loader')
.loader('svg-sprite-loader')
.options({
symbolId: 'icon-[name]',
})
// 修改images loader 添加svg处理
const imagesRule = config.module.rule('images')
imagesRule.exclude.add(path.resolve(__dirname, 'src/assets/icons'))
config.module
.rule('images')
.test(/\.(png|jpe?g|gif|svg)(\?.*)?$/)
}
}
4、封装组件:在src/compoments/下创建SvgIcon.vue
<template>
<svg :class="svgClass" aria-hidden="true">
<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>
5、在main.js文件中注册为全局组件
import Vue from 'vue';
import App from './App.vue';
import './assets/icons/index.js';
import SvgIcon from './components/SvgIcon.vue';
Vue.component('svg-icon', SvgIcon);
Vue.config.productionTip = false;
new Vue({
render: h => h(App),
}).$mount('#app')
6、使用
<template>
<div>
<svg-icon class-name="chilun-icon" icon-class="chilun"/>
//说明:这里的className的作用是为当前这个icon添加一个类名,也就是你可以通过这个类型对这个icon设置样式,这个案例就是加了个chilun-icon类,css在下面
// icon-class 这个很重要,这里是你想用的svg文件名,也就是说你想用的svg文件叫什么这里就填写什么。
</div>
</template>
<script>
export default {
name: 'test',
}
</script>
<style>
.chilun-icon {
font-size: 30px;
color: gold;
}
</style>
效果展示: