Skip to content

Instantly share code, notes, and snippets.

@jeremiegirault
Last active December 9, 2022 02:10
Show Gist options
  • Save jeremiegirault/fa0a826a2e3a205792e59abfaf377d67 to your computer and use it in GitHub Desktop.
Save jeremiegirault/fa0a826a2e3a205792e59abfaf377d67 to your computer and use it in GitHub Desktop.
Use inline SVG in vue.js

Install svg-inline-loader for webpack :

npm install svg-inline-loader --save-dev

Add it to your loaders in module.loaders section of webpack.config.js:

{
  test: /\.svg$/,
  loader: 'svg-inline-loader'
}

And now the tricky thing is to modify your vue-loader options to use require for vector:src attribute which will in turn use the svg-inline-loader:

transformToRequire: {
  // use for vector:src
  vector: 'src',
  // img:src & image:xlink:href url transform (vue default)
  // https://github.com/vuejs/vue-loader/blob/master/docs/en/options.md
  img: 'src', image: 'xlink:href'
}

(optional) Use vector as a top-level component:

import Vector from './Vector'
Vue.component('vector', Vector)

And now in your .vue files you can use it like "traditional" images :

<template>
  <div>
    <vector src="~assets/my-image.svg"></vector>
  </div>
</template>
<style scoped>
</style>
<template>
<div v-once v-html="src">
</div>
</template>
<script>
// see vue-loader.conf
export default {
props: [ 'src' ]
}
</script>
@clintonyeb
Copy link

Default vue-webpack template already defines svg to be loaded by url-loader. Make sure to remove svg from the list.

From:

{
        test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: utils.assetsPath('img/[name].[hash:7].[ext]')
        }
      }

To:

{
        test: /\.(png|jpe?g|gif)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: utils.assetsPath('img/[name].[hash:7].[ext]')
        }
      }

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