0

I am passing url to local images stored in the ~/assets/img folder to a Vue3 component, but I am not able to render them by any means.

THIS WORKS

<img
  src="~/assets/img/tds_logo.png"
/>

BUT THIS DOES NOT WORK

<img
  :src="require(`~/assets/img/` + fileName)"
/>

the last literal fileName is something I am passing to a Vue component to render the img and I have checked that that is equal to tds_logo.png in my case.

Instead I get this error: [nitro] [dev] [unhandledRejection] Error: Cannot find module '~/assets/img/tds_logo.png'

Does anyone know what I am doing wrong?

As per this https://nuxtjs.org/docs/directory-structure/assets/ I shouldn't need to configure anything, right?

Pratyush
  • 171
  • 1
  • 8
  • Have a look at [what is `require()` in Javascript](https://stackoverflow.com/a/9901097/4883195). If you actually want to load the image as a module, you need to have proper loaders and load the image at the top of the file. – Moritz Ringler Mar 26 '23 at 19:10

1 Answers1

0

Vite does not have inbuilt require like webpack and only has import.

In Nuxt3 / Vue3

write a method for the component like below:

 props: ['imagename'],
 methods: {
    getImageUrl(imagename) {
      const imageUrl = new URL(`/assets/img/${imagename}`, import.meta.url).href
      return imageUrl;

    }
  }

and then use this method in the template:

<img
:src="getImageUrl(imagename)"
  
/>
Pratyush
  • 171
  • 1
  • 8