JacobBrown2019
JacobBrown2019

Reputation: 115

import svg file from local directory without using vue-svg-loader

I just want to know if it's possible to import an svg file from local folder to a ".vue" file.

--home directory
  --> page.vue
  --> svg-directory
      --> svgFile.svg

I want to import svgFile.svg inside page.vue, doing something like:

import ....

or:

<img src="./svg-directory/svgFile.svg" /> 

or something else.

thanks for the help

Upvotes: 0

Views: 2841

Answers (1)

tao
tao

Reputation: 90068

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.

Upvotes: 3

Related Questions