Efficiently uploading numerous SVGs in vue.js using vue-svg-loader

Is there a more efficient way to import multiple SVGs in a Vue component without having to individually import each one as suggested in the documentation?

Check out vue-svg-loader documentation:

<script>
import Info from "@/assets/svgs/info.svg";
import Help from "@/assets/svgs/help.svg";
import Close from "@/assets/svgs/close.svg";
// and so on.

export default {
  components: {
    Info,
    Help,
    Close
  }
</script>

But what if I need to import over a hundred SVGs? How can I streamline this process?

Any suggestions or solutions?

Answer №1

To optimize your workflow, consider creating a base component and registering it globally for frequent use.


Start by developing a <BaseIcon> component that leverages the require with expression method to establish a context for SVG modules:

<template>
  <Component
     :is="require(`@/assets/svgs/${name}.svg`).default"
     class="BaseIcon"
     v-bind="$attrs"
     @v-on="$listeners"
  />
</template>

<script>
export default {
  name: 'BaseIcon',

  inheritAttrs: false,
  
  props: {
    name: {
      type: String,
      required: true,
    },
  },
}
</script>

<style>
 .BaseIcon {
   /* Define default CSS styles */
 }
 </style>

Tip: The usage of <Component> is geared towards managing dynamic components, assuming integration with vue-svg-loader where SVGs are treated as components. For different scenarios, employ an <img> tag using src instead of is.


To make the base component accessible globally:

If you have a single base component, simply open your main.js file and include these lines before mounting the app:

import Vue from 'vue'
import BaseIcon from './components/_base/BaseIcon.vue'
import App from './App.vue'

Vue.component('BaseIcon', BaseIcon)

Vue.config.productionTip = false

new Vue({
  render: h => h(App),
}).$mount('#app')

For more intricate setups, explore how this boilerplate automates base component registration.


To utilize the component effectively, follow this structure:

<template>
  <div>
    <BaseIcon
      name="info"
    />
    <BaseIcon
      name="help"
    />
    <BaseIcon
      name="close"
    />
  </div>
</template>

<script>
export default {
  name: 'SomeComp',
}
</script>

Answer №2

Regrettably, the solution outlined in this particular response did not yield the desired results for my case (using Vue-CLI 3 with Vue 2).

For instance, when attempting to incorporate an external SVG file:

    <img :src="require(`@/assets/img/icons/base/config.svg`).default" />

Or employing an inline SVG through a dynamic component:

    <component :is="require(`@/assets/img/icons/base/config.svg?inline`)" />

Similarly, utilizing an inline SVG within a conventional component:

<template><config-icon /></template>
import ConfigIcon from '@/components/icons/config-icon.vue';

To integrate this functionality, it's essential to include the following code snippet within your vue.config.js file:

      chainWebpack: (config) => {
       const svgRule = config.module.rule('svg');

       svgRule.uses.clear();
       svgRule.delete('type');
       svgRule.delete('generator');

       svgRule
        .oneOf('inline')
        .resourceQuery(/inline/)
        .use('babel-loader')
        .loader('babel-loader')
        .end()
        .use('vue-svg-loader')
        .loader('vue-svg-loader')
        .end()
        .end()
        .oneOf('external')
        .use('file-loader')
        .loader('file-loader')
        .options({
          name: 'assets/[name].[hash:8].[ext]',
        });
      },

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Choose a different option when there is a change

Here is an example of JSON data: [{ "user_id": "113", "employe_first_name": "Asaladauangkitamakan", "employe_last_name": "Nasibb" }, { "user_id": "105", "employe_first_name": "Ryan", "employe_last_name": ...

Does it follow standard practice for Array.filter to have the capability to also perform mapping on an array of objects?

While experimenting with Array.filter, I made an interesting discovery. By forgetting to include an equality check, my array was unexpectedly mapped instead of filtered. Here is the code snippet that led to this result: const x = [{ name: 'user' ...

Ways to access the variables of an object that initiated a function, leading to another function being called

I am facing an issue with accessing the variable b from inside the callback of setTimeout. I understand that the callback function of setTimeout only has access to the variables within its surrounding function. How can I access the this.b? Thank you! fu ...

A guide on efficiently mapping all items from an object containing an unspecified number of items or item names within a reusable component

I am currently exploring the concept of building reusable components. In a personal project, I am in the process of mapping items retrieved from a database. My goal is to create a component that can dynamically map any number of unspecified types as table ...

router.query is returning an empty object when using Next.js

Here is how my folders are organized: https://i.stack.imgur.com/TfBtv.png In addition, here is a snippet of my code: const router = useRouter(); const { id } = router.query; The issue I'm facing is that the id is returning {} instead of the actual ...

Step-by-step guide for inputting a sophisticated formula in exceljs using JavaScript

Currently, I am working on a project that involves exporting data into multiple xlsx sheets. One of the sheets requires me to add a formula in cells that meet certain conditions before adding data from the first sheet. Here is an example: Ref !== null ? wo ...

Tips for minimizing a collection of objects?

Currently, I am working on developing a unique quiz format where there are no correct or incorrect answers; instead, responses are given a score ranging from 1 to 4. Each question falls under one of four distinct categories (such as cat, dog, rabbit, alpa ...

What is the best way to link an ASP.NET byte array to a file input field in a form?

In my ASP.NET project, I am looking to send a POST request to a third-party service for document editing (Zoho). While I have experience with making such requests using front-end forms and VB.NET in the code-behind, integrating both becomes tricky due to t ...

Understanding how to sum the values of two separate dropdown selections using jQuery

Is it possible to combine and total up two different selections to display on the "Total" button below? I have added calculations to each selection. When a user selects a quantity, it should automatically sum up and display on the "Total" button, but I am ...

Invoking a function sharing the same name as a local variable

The code snippet below is causing me some trouble... var firstPlay = 1; if (firstPlay == 1) { firstPlay(); } If I remove the if statement and simply have: firstPlay(); It works fine, but for some reason it doesn't work with the if statement. ...

React JS - Sending props from Dev and Build to App component

Looking to include static assets and props in my App, specifically having image assets set with a base64 string in the build process. Want to ensure these assets are accessible to the App's props before development and build stages, similar to the fun ...

Markers on the map are not receiving the necessary click event handlers

The block of code below is designed to place markers on a map. However, it seems that the add Listener event is not properly attached to each marker. var mapDiv = document.getElementById("google-map"); var infoWindow = new google.maps.InfoWindow({ ...

featherlight.js - Execute code when modal is triggered

Situation with HTML <div id="form-lightbox"> <div class="form"> <div id="ajaxreplace"> <script type="text/javascript"> jQuery(function() { jQuery.ajaxReplace({ //parame ...

Jest: Issue with spyOn test failing despite async function being executed

Having trouble setting up a spyOn for an async function within a submodule. This issue is throwing me off because I've successfully implemented similar tests in the past. Here's an overview of the code: In routes.js: const express = require(&apo ...

Utilizing AngularJS routes to load a specific URL when accessing a page for the first time

Working on developing a Single Page Application using AngularJS, my configuration settings appear as follows: app.config(["$routeProvider", function($routeProvider) { return $routeProvider .when("/", { redirectTo: " ...

Ensuring correct association of values to avoid redundancies

There are 5 fields available for users to fill out on this form: Leave Code, From Date, Input Time1, To Date, and Input Time2. These variables are declared as a dates object in the .ts file, as shown below. interface Supervisor { name: string; code: s ...

Achieving cell merging in react-table can be accomplished by utilizing the appropriate

Currently, I am using react-table and have the need to combine cells in specific columns based on their content. Essentially, I want to remove the divider border between these merged cells. To give you a visual idea, this is how it currently looks like: h ...

Undefined Javascript variables are commonly found within loops

My code includes a loop that fetches an array of users and attempts to retrieve the information of each user. However, I've encountered an issue where if there are multiple users, it ends up returning the same information (specifically, the details of ...

"Encountering a delay in the passport authentication callback process

After multiple attempts to solve this issue independently, I have turned to the Stack Overflow community in search of guidance. I am implementing user authentication using passport. It has already been initialized in my main express.js file following the ...

Share information from Vuex getter to component property

I'm seeking a way to retrieve data from the Vuex config state and pass it as a prop to a component for an autocomplete feature. I am struggling with the correct syntax to achieve this. My attempts so far have been unsuccessful. Would it be necessary ...