How to import an SVG file to a Vue.js component?

Sometimes, we want to import an SVG file to a Vue.js component.

In this article, we’ll look at how to import an SVG file to a Vue.js component.

How to import an SVG file to a Vue.js component?

To import an SVG file to a Vue.js component, we can add the vue-svg-loader Webpack plugin into our Vue project.

We install vue-svg-loader by running

npm install --save-dev vue-svg-loader

Then, we write

module.exports = {
  module: {
    rules: [
      {
        test: /.svg$/,
        use: ["babel-loader", "vue-svg-loader"],
      },
    ],
  },
};

in our Webpack config.

Then we can import SVGs as a module with

<template>
  <nav id="menu">
    <a href="...">
      <Icon class="icon" />
    </a>
  </nav>
</template>

<script>
import Icon from "@/assets/icon.svg";

export default {
  name: "menu",
  components: {
    Icon,
  },
};
</script>

We register the Icon SVG component, register it, and then add it into our template.

Conclusion

To import an SVG file to a Vue.js component, we can add the vue-svg-loader Webpack plugin into our Vue project.