JetBrains / svg-sprite-loader

Webpack loader for creating SVG sprites.
MIT License
2.02k stars 271 forks source link

Is there has some way to extract every single svg file? #416

Closed yunyuyuan closed 3 years ago

yunyuyuan commented 3 years ago

svg-sprite-loader is a very fantastic project.I have a question when i use it: I have tried to use extract: true,but it seems that all the SVGs will be packed into one sprite.svg file that has big size,and all svg file would be load at sprite.it's waste of resources in some web page that only used a few svg files. Can i extract all svg to multiple files,then i can load them on demand?

yunyuyuan commented 3 years ago

Okey,I have found a solution; vue.config.js

    chainWebpack: config => {
        config.module
            .rule('svg')
            .exclude.add(path.resolve('src/icons'))
            .end();
        config.module
            .rule('icons')
            .test(/\.svg$/)
            .include.add(path.resolve('src/icons'))
            .end()
            .use('svg-sprite-loader')
            .loader('svg-sprite-loader')
            .options({
                symbolId: 'icon-[name]'
            });
    }

index.js

import Vue from 'vue'
import IconSvg from '@/icons/IconSvg'// svg组件

// register globally
Vue.component('svg-icon', IconSvg)

SvgIcon.vue

<template>
  <svg aria-hidden="true">
    <use :xlink:href="getName"></use>
  </svg>
</template>

<script>
export default {
  name: "IconSvg",
  props: {
    name: {
      type: String,
      default: ''
    }
  },
  computed: {
    getName() {
      import(`@/icons/svg/${this.name}.svg`)
      return `#icon-${this.name}`
    }
  }
}
</script>

<style scoped lang="scss">
</style>