Skip to content

Instantly share code, notes, and snippets.

@imfing
Last active April 22, 2021 06:44
Show Gist options
  • Save imfing/f13798f98093b94b937e1bc92535ff05 to your computer and use it in GitHub Desktop.
Save imfing/f13798f98093b94b937e1bc92535ff05 to your computer and use it in GitHub Desktop.
Using inline SVGs in Vue components

An alternative way to implement "dynamic" svg is using html-loader.

First, create a component for svg, SvgIcon.vue:

<template>
  <div v-html="require(`../../assets/icon-${icon}.svg`)"></div>
</template>

<script>
export default {
  props: ['icon']
}
</script>

Then, in vue.config.js, modify webpack config and use html-loader as the loader for .svg file. Remember to add the dependency: $ yarn add html-loader --dev

module.exports = {
  chainWebpack: config => {
    const svgRule = config.module.rule('svg')
    svgRule.uses.clear()
    config.module
      .rule('svg')
      .test(/\.svg$/)
      .use('html-loader')
      .loader('html-loader')
      .end()
  }
};

Now you can use the svg component directly, the svg will be loaded and inserted inline:

<svg-icon icon="close" />

Reference:

http://calebporzio.com/using-inline-svgs-in-vue-compoments/

laravel-mix/laravel-mix#1423

https://markus.oberlehner.net/blog/dynamically-loading-svg-icons-with-vue/

https://github.com/webpack-contrib/svg-inline-loader

https://cli.vuejs.org/guide/webpack.html#simple-configuration

@clonesia
Copy link

whats wrong ?
Screenshot_71

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment