0

using Vite I need to import image url for example with the way like this

 <svg :src="import('®/@material-icons/svg/1k/outline.svg')"></svg>

but instead of url I'm getting src="[object Promise]" is there any ways to make it work correctly?

Boussadjra Brahim
  • 82,684
  • 19
  • 144
  • 164
alexanne
  • 131
  • 7

2 Answers2

3

You have to use require

<svg :src="require('®/@material-icons/svg/1k/outline.svg')"></svg>

Ensure to have the correct path for the file

Fore Vite

<svg :src="svgPath"></svg>

<script>
  async created(){
    this.svgPath = (await import("®/@material-icons/svg/1k/outline.svg")).default()
  }
  data(){
    return {svgPath:""}
  }
</script>
Kaneki21
  • 1,323
  • 2
  • 4
  • 22
  • but require is not working with Vite – alexanne Sep 19 '22 at 03:02
  • 1
    Edited. Please try. I came across with this [solution](https://stackoverflow.com/questions/69696677/vite-vue-3-require-is-not-defined-when-using-image-source-as-props) – Kaneki21 Sep 19 '22 at 03:06
  • thank you, but seems vue render works synchronously and I cannot use await( I'm getting 'await' is only allowed within async functions and at the top levels of modules. and I don't know is there any ways to change templates render type to async – alexanne Sep 19 '22 at 03:08
  • 1
    I've updated the answer, give it a try – Kaneki21 Sep 19 '22 at 03:20
  • yep, thanks, that works, but that's a lot of code if compare with require using webpack, is there any plugins to make that shorter)? – alexanne Sep 19 '22 at 03:26
  • 1
    You can make an utility function in a separate file, and pass the path as parameter and return the default value – Kaneki21 Sep 19 '22 at 03:32
1

The easiest way to work with images in Vitejs is to place images inside the public folder then use them without any import, Assume that we have a folder named svg inside the public one :

<svg src="/svg/1k/outline.svg"></svg>

Or import it as module then bind it to the src attribute :

<template>
  <svg :src="imgUrl"></svg>
</template>
<script setup>
   import imgUrl from '®/@material-icons/svg/1k/outline.svg'
</script>
Boussadjra Brahim
  • 82,684
  • 19
  • 144
  • 164
  • thanks but I'm using @material-icons/svg which are located in node_modules seems the only problem I have is I have 30+ svgs and that's pretty hard to remember name of every variable using import every time in script(( – alexanne Sep 19 '22 at 13:52