'Vue 3 + Vite image URL becomes undefined after build

I encountered a bug where I dynamically generated a URL from props for image import in my Vue 3 component and it becomes undefined after build

  • Script used to generate URL and the tag in Vue Component
const imagePath = computed(() => { return new URL(`../assets/${props.imgPath}.png`,
    import.meta.url).href

<img :src="imagePath" />
  • Undefined URL after build <img class="img" src="http://localhost:4173/undefined />

Only two out of the many images are undefined after build which makes it very hard to pin down the problem

I tried messing around with vite.config.ts, particularly assetInlineLimit under the build section but so far nothing works



Solution 1:[1]

I was having the same issue and found that you need to set the build target to 'es2020' since import.meta.url is not defined in the default build target. There is a small note at the bottom of this page: https://vitejs.dev/guide/assets.html

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 brenzy