Is it possible for dynamic importing of @mdi/js icon to function efficiently with tree-shaking in a vue template?

One interesting challenge I've encountered involves dynamically importing icons from mdi/js. The issue at hand is that tree-shaking does not seem to work with this setup. Does anyone have any insights on how to enable tree-shaking in this scenario? This component can be used anywhere like

<Icon name='mdiMagnify'>

Icon.vue

<template>
    <v-icon v-bind="$attrs">{{ icon }}</v-icon>
</template>

<script>
export default {
    name: 'Icon',
    props: {
        name: {
            required: true,
            type: String,
        },
    },
    data: () => ({
        icon: null,
    }),
    async created() {
        const { [this.name]: icon } = await import('@mdi/js')
        this.icon = icon
    },
}
</script>

The main advantage of this approach is that there's no need to individually import each icon for every component and store it in a data variable just to use it in Vue templates.

Answer №1

If you happen to be utilizing nuxt.js (which seems likely given the tag on your query), implementing custom icons is a breeze. Simply include the following snippet in your nuxt.config.js:

vuetify: {
  defaultAssets: false,
  treeShake: true,
  icons: {
    iconfont: 'mdiSvg',  // --> this should suffice

    // Additional Info: You also have the option to define personalized values and access them throughout your application without importing them into each component

    values: {
      plus: mdiPlus, // By using $vuetify.icons.values.plus, you can easily access this icon in your components
    }
  }
}

In order for these defined values to function properly, you must import the relevant icon within the nuxt.config.js file:

import { mdiPlus } from '@mdi/js'

Alternatively, if you prefer not to use custom values, you can import necessary icons directly within individual components and utilize them as needed:

import { mdiPlus } from 'mdi/js'
...
data() {
  return {
    plusIcon: mdiPlus
  }
}

Answer №2

My current solution involves storing all the svg files in the @mdi/svg package and using them as img sources. This eliminates the need for dynamically importing from @mdi/js and relying on treeshake optimization.

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

In a Vue Application, the static HTML elements are loaded before fetching data

Utilizing VueJS and VueRouter in my application has presented a challenge. The issue lies in the fact that static HTML elements within the Vue Component load before the data is fetched, resulting in empty forms and tables being displayed initially. I have ...

Attempting to insert an element after the .load event has been triggered

I have been attempting to update the contents of ".myShop" after it's loaded from an external XML file, but without success. I believe my timing is correct, but I suspect that a loaded element may not be part of the DOM? Here's what I'm exp ...

variables that have been declared as jquery elements

What are the recommended practices for declaring jQuery DOM elements as variables? Is there any distinction between var div = $('div'); and var $div = $('div'); other than improved readability? Thank you ...

When combining CSS grids, nesting them can sometimes cause issues with the height layout

Check out the code on jsFiddle .component-container { width: 800px; height: 200px; background-color: lightyellow; border: 1px solid red; padding: 10px; overflow: hidden; } .component-container .grid-container-1 { display: grid; grid-tem ...

The top row of a Bootstrap table generated with JavaScript does not display the background color as intended

I am currently using JavaScript to generate some HTML that displays a Bootstrap table. Below is the code for creating this: function displayTableData(d){ let html = ''; html += '<table id="my-table" class="table&q ...

Employ multiple directives to include data attributes within components

I am experiencing an issue with two directives that are meant to add data attributes to components for testing purposes. Surprisingly, only one of the directives actually gets added. The components in question are Bootstrap-Vue's BFormInput and BButto ...

Integrate ruby code within a javascript string

I am looking to insert tfx-<%= @doc.doc[:b].metadata['filename']} %> into a JavaScript string called 'url' url = "<%= @document.doc[:a].url(response_content_disposition: ContentDisposition.attachment( [INSERT HERE] )) %>"; ...

Dynamic loading in React Plugin Architecture allows for flexibility in organizing and incorporating

My goal is to develop a Single Page Application on the client side that incorporates a plugin architecture. The requirement is for users to be able to place a package in a designated folder, which will then be loaded by the server after a restart. These pl ...

Recording Audio Using ReactJS

I am exploring ways to record audio using ReactJS and save it on my Node server. Initially, I attempted to utilize the "react-audio-recorder" module but encountered issues when attempting to record multiple audios consecutively. Additionally, I experiment ...

Angular ng-repeat with toggle filter

Looking for a way to display data in an angular application using ng-repeat? Want to add and remove filters on the displayed data with a simple click? You're in luck. Implementing a toggle filter functionality is easier than you think. If you've ...

Only apply the hover effect in jQuery when the scrollTop position is equal to zero

I want to implement a hover effect on my header, specifically when the user is at the top of the page. I am working with Shopify and believe the best approach is to add a class when hovering over it and change certain CSS properties (such as text color a ...

Prolong the Slide Duration in Slider Pro Slideshow

I am currently utilizing Slider Pro from bqworks.com for a slideshow with automated cycling on my website. I would like to adjust the display duration of each image in the slideshow. The documentation mentions a property called "slideAnimationDuration," wh ...

Choosing a line object with the mouse in Three.js

How can I select a line object in threeJS? I attempted to use raycaster for this purpose. http://jsfiddle.net/nelsonlbtn/z43hjqm9/43/ Upon running the test, I encountered the following error: three.min.js:598 Uncaught TypeError: d.distanceTo is not a f ...

Creating a Cordova application from the ground up, evaluating the options of using ngCordova, Ionic framework, and

With the goal of creating a multiplatform Cordova app for Android, iOS, and Windows, I have been exploring different approaches. My plan is to build an application with 4 or 5 features focused on service consumption (listing, adding, and editing items) wh ...

Send the form after the asynchronous validator resolves its promise in AngularJS

My async validator 'username-validator' was designed to check for username availability without making multiple remote calls. To achieve this, I decided to update the ng-model on the 'blur' event rather than on every 'key press&apo ...

How can you use CakePHP3 to incorporate user notifications in a style similar to Facebook or a stack format through view cells?

When using platforms like Facebook or StackOverflow, we often receive notifications on the top navigation bar without refreshing the webpage. These are known as push notifications. I have a functional CakePHP 3 web app and my client wants to incorporate t ...

Executing a C# program that sends a web request without using JavaScript

My goal is to programmatically download the contents of a website, but it seems like this content is being loaded through ajax calls. Interestingly, when I disable javascript in my browser, only one request is made by the page and all the content is displa ...

Angular's expression is incapable of determining the variable's type through the use of the constructor property

I attempted to use an angular expression to determine if a scope variable is an array. However, when using variable.constructor === Array for the check, the result always showed as false. It was only when I used a scope function with return variable.const ...

Can you pinpoint the issue with this asynchronous function in Vue3?

Dealing with a simple concept error, I find myself unable to solve it. Within the onMounted hook, everything looks correct - an Array of three objects is displayed. However, when I return it to the template and try to interpolate it, all I see is an empty ...

Learn how to display a loading message instead of a blank page while your Vue.js application is loading

Whenever a new Vue.js page is accessed, there is a brief moment where a blank, white page is displayed until the entire application finishes loading. I have attempted multiple times to display a loading message first using the traditional method, but eve ...