The issue you're encountering is related to how Vite handles dynamic imports. When using dynamic imports with variables, Vite needs to be able to resolve the path at build time, which can be problematic with variable paths. However, there are ways to work around this limitation.
Here's a solution that involves creating a mapping of your icons and using that to dynamically import them:
-
Create a mapping of your icons: You can create a JavaScript object that maps icon names to their respective import paths.
-
Use the mapping to dynamically import the icons: Use the mapping to resolve the correct path for the icon you want to import.
Here's how you can implement this:
// Create a mapping of icon names to their import paths
const iconMap = {
SunIcon: () => import('@heroicons/vue/24/solid/SunIcon.js'),
// Add other icons here
// Example: MoonIcon: () => import('@heroicons/vue/24/solid/MoonIcon.js'),
};
// HeroIcon.vue
<template>
<component :is="iconComponent" />
</template>
<script setup>
import { defineAsyncComponent, ref } from 'vue';
import { onMounted } from 'vue';
// Props to accept the icon name
const props = defineProps({
name: {
type: String,
required: true,
},
});
const iconComponent = ref(null);
onMounted(() => {
if (iconMap[props.name]) {
iconComponent.value = defineAsyncComponent(iconMap[props.name]);
} else {
console.error(`Icon "${props.name}" not found.`);
}
});
</script>
-
Use the component in your application: Now you can use the
HeroIconcomponent and pass the icon name as a prop.
<!-- Dashboard.vue -->
<template>
<HeroIcon name="SunIcon" />
</template>
<script>
import HeroIcon from '@/Components/HeroIcon.vue';
export default {
components: {
HeroIcon,
},
};
</script>
Explanation:
-
Icon Mapping: The
iconMapobject maps icon names to their respective import functions. This allows you to dynamically import the correct icon based on the name provided. -
Dynamic Component: The
<component :is="iconComponent" />tag in the template dynamically renders the component thaticonComponentresolves to. -
Error Handling: If an icon name is not found in the
iconMap, an error is logged to the console.
This approach allows you to keep your code DRY and manage icons more efficiently across your application. You can expand the iconMap with more icons as needed.