meowtec / vite-plugin-svg-sprite

SVG sprite plugin for [vite](https://github.com/vitejs/vite)
MIT License
52 stars 10 forks source link

Dynamic import support #14

Open seahindeniz opened 1 year ago

seahindeniz commented 1 year ago

Hi Instead of importing SVG files individually, can we use a dynamic import?

For example,

<script setup lang="ts">
import { computed, onBeforeMount, ref } from 'vue';

export interface Props {
    name: string;
    /**
     * In pixels
     */
    size?: number | string;
}

const props = withDefaults(defineProps<Props>(), {
    size: 16,
});

const iconId = ref('');
const sizeInPx = computed(() => (String(props.size).endsWith('px') ? props.size : `${props.size}px`));

onBeforeMount(async () => {
    iconId.value = (await import(`../assets/icons/${props.name}.svg`)).default;
});
</script>

<template>
    <span
        :class="$style.container">
        <svg :class="$style.svg">
            <use :xlink:href="`#${iconId}`"></use>
        </svg>
    </span>
</template>

<style module lang="scss">
.container {
    width: v-bind(sizeInPx);
    height: v-bind(sizeInPx);
    display: block;
}

.svg {
    width: 100%;
    height: 100%;
}

.container, .svg {
    color: inherit;
}
</style>
meowtec commented 1 year ago

It seems to have been implemented indeed.

meowtec commented 1 year ago

There is a dynamic import example at https://github.com/meowtec/vite-plugin-svg-sprite/blob/main/examples/vite-svg-sprite-example/src/components/Dynamic.vue#L33 and it works.