安裝
yarn add svg-sprite-loader
使用
index.js
import Vue from 'vue'
import SvgIcon from '@/components/SvgIcon' // svg組件
// register globally
Vue.component('svg-icon', SvgIcon);
//自動引入 @/src/icons
const requireAll = requireContext => requireContext.keys().map(requireContext);
const req = require.context('./svgIcon', false, /\.svg$/);
requireAll(req);
SvgIcon.vue
<template>
<svg :class="svgClass" aria-hidden="true">
<use :xlink:href="iconName"></use>
</svg>
</template>
<script>
export default {
name: 'svg-icon',
props: {
iconClass: {
type: String,
required: true
},
className: {
type: String
}
},
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;
margin-right: 8px;
}
</style>
vue.config.js
const path = require('path')
const resolve = (dir) => path.join(__dirname, '.', dir)
module.exports = {
css: {
/*爲預處理器 loader 傳遞自定義選項*/
loaderOptions: {
sass: {
prependData: `@import "@/assets/scss/common.scss";`
}
}
},
publicPath: '/main',
devServer: {
// open: false,
// disableHostCheck: true,
host: 'fun.com',
port: 4000,
https: false,
hotOnly: false,
proxy: {
'/': {
target: '...',
secure: false, // 接受 運行在 https 上的服務
ws: false,
changeOrigin: true
}
}
},
chainWebpack(config) {
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()
}
}
最後在 main.js 中引入
import '@/icons'