Dynamic assets import inside Vue 3 component

Viewed 239

I need to inline SVG's on a component, but I don't know which SVG is going to be used as it's defined on the response to an endpoint request. I know there are libs/tools that I can add to the project but I'm trying to avoid them. I saw an example on Vue docs [https://vitejs.dev/guide/assets.html#importing-asset-as-string], but on the example, it's when you know which SVG's you going to use. So, I'm trying to do the same but in a dynamic way. It's working on dev mode, but when I build the app and run the preview I get the error 'Cannot find module'

This is one of the tests I did, but not sure if it's really possible to this and I need to adjust something on my implementation or if just impossible to do this way

<script setup lang="ts">
....
const getSvgIcons = () => Promise.resolve(import(/* @vite-ignore */`/src/assets/images/${brand}/icons/${icon.value}.svg?raw`)).then((res) => {
    return res.default
});
const svgIcon = computed(() => {
    try {
        return getSvgIcons()
    } catch (error) {
        throw new Error(error)
    }
});
...
</script>

<template>
    <a v-if="isExternalLink" target="_blank" class="base-link" :href="url">
        <span class="base-link__item">
            <i
                v-if="displayIcon"
                :class="`base-link__icon base-link__icon--${iconPosition}`"
                v-html="svgIcon"
            ></i>
            {{ text }}
        </span>
    </a>
    <router-link v-else class="base-link" :to="url">
        <span class="base-link__item">
            <i
                v-if="displayIcon"
                :class="`base-link__icon base-link__icon--${iconPosition}`"
                v-html="svgIcon"
            ></i>
            {{ text }}
        </span>
    </router-link>
</template>
0 Answers
Related