網上大多數的教程都是vue cli舊版的,通過這些教程導入Vue cli 4.0 可能會出問題。使用vue cli 3/4搭建項目使用svg自動導入的方法:
1、安裝 svg-sprite-loader、svgo這兩個庫
npm install --save-dev vue-svg-sprite-loader
npm install -g svgo
2、在根目錄創建vue.config.js,如果存在就不需要創建,然後添加一下配置
const path = require('path')
function resolve(dir) {
return path.join(__dirname, dir)
}
module.exports = {
devServer: {
disableHostCheck: true
},
chainWebpack(config) {
// set 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()
}
}
3、在src的目錄下創建一個icons文件夾、再創建一個index.js、mysvg.vue(這個vue組件命名隨意)和創建一個svg文件夾這個文件夾是存放svg的mysvg 文件的代碼,僅供參考
<template>
<svg :class="svgClass" aria-hidden="true" mode="open" v-on="$listeners" :style="{width: size,height:size}">
<use :xlink:href="iconName"/>
</svg>
</template>
<script>
// 這裏添加了一個size prop 是用來在外部控制svg的大小
export default {
name: 'SvgIcon',
props: {
iconClass: {
type: String,
required: true
},
className: {
type: String,
default: ''
},
size: {
type: String,
default: '14px'
}
},
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>
index.js 文件配置
// index文件配置
import Vue from 'vue'
import SvgIcon from './mysvg'// svg組件
// register globally
Vue.component('svg-icon', SvgIcon)
const req = require.context('./svg', false, /\.svg$/)
const requireAll = requireContext => requireContext.keys().map(requireContext)
requireAll(req)
4.然後在 mian.js 中引用index.js
歡迎評論點贊!您的支持是我創作的動力!感謝支持!
歡迎關注公衆號“程序員轉管理”獲取更多優質文章