Most tutorials on the web are older versions of vue CLI, and importing vue CLI 4.0 from these tutorials can be problematic. Use Vue CLI 3/4 to build a project using SVG automatic import method: 1, install svG-sprite-loader, svGO these two libraries
npm install --save-dev vue-svg-sprite-loader
npm install -g svgo
Copy the code
Create vue.config.js in the root directory. If it exists, you don’t need to create it
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()
}
}
Copy the code
3. Create an ICONS folder in the SRC directory, an index.js folder, mysvg.vue(the vue component is named arbitrarily), and create an SVG folder. This folder is the code for storing the mysvg file of SVG
<template>
<svg :class="svgClass" aria-hidden="true" mode="open" v-on="$listeners" :style="{width: size,height:size}">
<use :xlink:href="iconName"/>
</svg>
</template>
<script>
// Add a size prop to control the size of SVG externally
export default {
name: 'SvgIcon'.props: {
iconClass: {
type: String.required: true
},
className: {
type: String.default: ' '
},
size: {
type: String.default: '14px'}},computed: {
iconName() {
return `#icon-The ${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.15 em;
fill: currentColor;
overflow: hidden;
}
</style>
Copy the code
Index.js file configuration
// index file configuration
import Vue from 'vue'
import SvgIcon from './mysvg'/ / SVG components
// register globally
Vue.component('svg-icon', SvgIcon)
const req = require.context('./svg'.false./\.svg$/)
const requireAll = requireContext= > requireContext.keys().map(requireContext)
requireAll(req)
Copy the code
4. Then reference index.js in mian.js