Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 507
Paulie Avatar asked Oct 17 '25 11:10

Paulie


1 Answers

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>
like image 187
flydev Avatar answered Oct 20 '25 00:10

flydev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!