1 安装
"svg-sprite-loader": "^6.0.9"
2 在src文件下创建一个icons文件夹 放入svg文件图片(阿里图标库) 并且配置一个index.js文件
import SvgIcon from '@/components/SvgIcon'
// https://webpack.docschina.org/guides/dependency-management/#requirecontext
// 通过 require.context() 函数来创建自己的 context
const svgRequire = require.context('./svg', false, /\.svg$/)
// 此时返回一个 require 的函数,可以接受一个 request 的参数,用于 require 的导入。
// 该函数提供了三个属性,可以通过 require.keys() 获取到所有的 svg 图标
// 遍历图标,把图标作为 request 传入到 require 导入函数中,完成本地 svg 图标的导入
svgRequire.keys().forEach((svgIcon) => svgRequire(svgIcon))
export default (app) => {
app.component('SvgIcon', SvgIcon)
}
3 在 components里面配置一个文件SvgIcon index.vue
<template>
<div
v-if="isExternal"
:style="styleExternalIcon"
class="svg-external-icon svg-icon"
:class="className"
/>
<svg v-else class="svg-icon" :class="className" aria-hidden="true">
<use :xlink:href="iconName" />
</svg>
</template>
<script setup>
import { isExternal as external } from '../../utils/validate'
import { defineProps, computed } from 'vue'
const props = defineProps({
// icon 图标
icon: {
type: String,
required: true
},
// 图标类名
className: {
type: String,
default: ''
}
})
/**
* 判断是否为外部图标
*/
const isExternal = computed(() => external(props.icon))
/**
* 外部图标样式
*/
const styleExternalIcon = computed(() => ({
mask: `url(${props.icon}) no-repeat 50% 50%`,
'-webkit-mask': `url(${props.icon}) no-repeat 50% 50%`
}))
/**
* 项目内图标
*/
const iconName = computed(() => `#icon-${props.icon}`)
</script>
<style scoped>
.svg-icon {
/* width: 1em;
height: 1em; */
vertical-align: -0.15em;
fill: currentColor;
overflow: hidden;
}
.svg-external-icon {
background-color: currentColor;
mask-size: cover !important;
display: inline-block;
}
</style>
4 在utils文件中添加一个validate.js文件
/**
* 判断是否为外部资源
* @param {*} path
*/
export function isExternal(path) {
return /^(https?:|mailto:|tel:)/.test(path)
}
5 在main.js里面设置
import installIcons from './icons'
installIcons(App)
6 在vue.config.js文件中配置
const { defineConfig } = require('@vue/cli-service')
const path = require('path')
function resolve(dir) {
return path.join(__dirname, dir)
}
module.exports = defineConfig({
transpileDependencies: true,
chainWebpack(config) {
// 设置 svg-sprite-loader
config.module.rule('svg').exclude.add(resolve('src/icons')).end()
config.module
.rule('icons')
.test(/\.svg$/)
.include.add(resolve('src/icons'))
.end()
.use('svg-sprite-loader')
.loader('svg-sprite-loader')
.options({
symbolId: 'icon-[name]'
})
.end()
}
})
7 在页面中就可以进行使用
<template>
<div>
<span class="svg-container">
<SvgIcon icon="gun" />
<SvgIcon icon="chart" />
</span>
</div>
</template>
<script>
import SvgIcon from './components/SvgIcon/index.vue'
export default {
name: 'App',
components: {
SvgIcon
}
}
</script>
<style scoped>
</style>