2

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

Ricey
  • 21
  • 1
  • 3

3 Answers3

4

I am a bit late. But for anyone still having this problem,

Similar to OP, this will not work.
It will return undefined. (http://localhost:5173/src/assets/icons/undefined)

const src = computed(() => {
    return new URL(`@/assets/icons/${props.src}`, import.meta.url);
});

Simply move the template literals into a variable.
And everything should work now.

const src = computed(() => {
    const path = new URL('@/assets/icons/', import.meta.url);
    return `${path}/${props.src}`
});

Apparently, new URL does not work well with template literals.
there's multiple bug report on this, and might be fixed in the future.
I am using vite 4.0 as of writing this post.

Cerceis
  • 770
  • 3
  • 14
2

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

brenzy
  • 1,976
  • 11
  • 20
0

I faced same problem, solution in my case, the image name must be like props name because it's case sensitive so I changed image name from "myimage.png" to "myiMage.png"

splinter.cell
  • 113
  • 1
  • 7