[Vuejs]-Import svg file from local directory without using vue-svg-loader

3👍

Vue uses webpack as asset bundler.

Webpack needs a loader for every single type of file it handles. Thankfully, you don’t need to write each loader, as they come pre-configured for the most common types. However, .svg is not one of the pre-configured ones.

If you want to load .svgs in webpack, you have to teach webpack how to handle those files, which is exactly what vue-svg-loader or svgo-loader do.
Obviously, you don’t have to use them. You can always write your own loader.

If you don’t want to write any loader, you could take advantage of the vue-loader, which is already present in a vue application. Simply wrap your <svg> in a <template> tag and save it as .vue:

<template>
  <svg>...</svg>
</template>

Now you can import and use it as you would any other component.

This also comes with the advantage of having the <svg> inline, which means it can inherit currentColor so you could easily animate its color (which you can’t when it’s loaded as an <img>).

See it working here: https://codesandbox.io/s/hopeful-lamarr-qjvkm?file=/src/App.vue


If you want to automate it and not have to wrap all the svgs in <template> tags and save them as .vue, here’s an article explaining how you could do it:
https://codeburst.io/managing-svg-images-in-vue-js-applications-88a0570d8e88
using this loader:

import Vue from 'vue';
const requireTemplate = require.context( '.?vue-template', false, /\.svg$/ );
context.keys().forEach( fileName => {
  const name = 'Svg' + fileName.replace( /^\.\//, '' )
    .replace( /\.svg$/, '' ) );
  const withRender = requireTemplate( fileName );
  const component = withRender( {} );
  Vue.component( name, component );
});

Now you can import any .svg as you would import a .vue component and use it as a component.

👤tao

Leave a comment