Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

225
Visualizações
dynamically loading SVG in Vue3 and Vite

I'm trying to convert my Vue2/Webpack app to Vue3/Vite.

In Vue2/Webpack, this works:

<div v-html="require('!!html-loader!../../assets/icons/' + this.icon + '.svg')"></div>

Html-loader is added with:

"html-loader": "1.3.2",

In Vue3/Vite this throws the error: ReferenceError: require is not defined

I've looked around for an example of doing this but don't see how to do this without knowing the name of the file at compile time. Is that possible?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You could also use Lazy Load Components technique with defineAsyncComponent from Vue3 - 🔗ref.

or import() like is shown by @tony19 in this answer:

<script>
const getServiceIcon = async iconName => {
  const module = await import(/* @vite-ignore */ `../assets/svg/${iconName}.svg`)
  return module.default.replace(/^\/@fs/, '')
}

export default {
  data() {
    return {
      icon: null,
      iconName: 'icon1', // icon1.svg
    }
  },
  watch: {
    iconName: {
      async handler(iconName) {
        this.icon = await getServiceIcon(iconName)
      },
      immediate: true,
    },
  },
}
</script>

<template>
  <button @click="iconName = 'icon2'">Change to another SVG</button>
  <img :src="icon" height="72" width="72" />
</template>
about 4 years ago · Juan Pablo Isaza Relatório

0

You can take a look at vite-svg-loader plugin, and load SVG files as Vue components.

about 4 years ago · Juan Pablo Isaza Relatório

0

Simply by creating a component where you will load the icons. Using composition API here.

<template>
    <i v-html="icon" />
</template>

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

    const props = defineProps(['icon', 'loading', 'src']);
    const icon = ref();
    const path = props.src ? props.src : '';
    const file = `${path}icon-${props.icon}`;
    const modules = import.meta.glob('../../assets/icons/**/*.svg', { as: 'raw' });

    function getViews(path: any) {
        return modules['../../assets/icons/' + path + '.svg'];
    }

    const getServiceIcon = async () => {
        return getViews(file);
    };
    watchEffect(async () => (icon.value = await getServiceIcon()));
</script>

This will allow you to even style your SVG using css, tailwind etc...

The usage:

<UiIcon icon="NAME" class="w-8 fill-current text-red-500"/>

Done.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda