skip to Main Content

I’m making a project with Vue3 + Vite and trying to set an adaptive src for the img:

<img :src="`@img/map_icons/${ currentMap.title }_icon.png`">

In vite.config i’ve created the alias:

'@img': resolve(__dirname, 'src/shared/assets/img')

But website doesn’t load my img and giving an error:

GET http://localhost:5173/@img/map_icons/ancient_icon.png 404 (Not Found)

The only way i find to do it correctly is by using relative src:

<img :src="`./../../shared/assets/img/map_icons/${ currentMap.title }_icon.png`">

So how can i set the src with using alias?

2

Answers


  1. This can be done with tsconfig.json or jsconfig.json. Create tsconfig.json or jsconfig.json file in your project’s root directory and add following fields

    {
      "compilerOptions": {
        "baseUrl": ".",
        "paths": {
          "@img": ["src/shared/assets/img"]
        },
        ...
       }
       ...
    }
    
    Login or Signup to reply.
  2. You can resolve all of your needed images as URLs (remember they all will be included in the build) and find an appropriate URL:

    const imageURLs = Object.values(import.meta.glob('@img/map_icons/*_icon.png', { as: 'url', eager: true }));
    
    <img :src="imageURLs.find(url => url.includes(`/${ currentMap.title }_`)">
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search