Search code examples
javascripthtmlvue.jsvuejs3vite

Weird image URL for dynamic import of images


I have a json file with image names

{
    "img": "placeholder.jpg",
    "title": "124 ave NW",
    "sqft": "1319",
    "bedrooms": "3",
    "bathrooms": "3"
  },

im trying to dynamically import these images based on the img name

<template>
  <div class="project">
    <img width="350px" height="300px" :src="getImgUrl(img)" class="project-image" />
    <h1 class="project-title">{{ title }}</h1>
    <div class="project-details">
      <div class="bedroom-container"><img :src="bedIcon" /> {{ bedrooms + ' bedroom' }}</div>
      <div class="bathroom-container"><img :src="bathIcon" /> {{ bathrooms + ' bathroom' }}</div>
      <div class="size-container">{{ sqft + ' Sq. Ft.' }}</div>
    </div>
  </div>
</template>

using a function getImgUrl to properly resolve that image import

const getImgUrl = (img: string) => {
  return new URL(`./assets/images/${img}`, import.meta.url).href
}

looking at this code to me i understand this as take the image name which is placeholder.jpg and append the proper url to it. This should come back as src/assets/images/placeholder.jpg

However when i take a look in dev tools i see the following url resolved for the img component http://localhost:5173/src/components/project-display-component/undefined

Im very lost and confused about this, how is it possible its getting the completely wrong URL

I have looked around at the vite guide for static assets: https://vitejs.dev/guide/assets.html

as well as added the base: './src' to my vite.config.ts under defineConfig

Am i missing some sort of vite config step?


Solution

  • If the images are in /src/assets/images, we wouldn't expect to find them in a subfolder below the current module. Instead of import.meta.url, start from the project root as the base...

    const getImgUrl = (img: string) => {
      return new URL(`/src/assets/images/${img}`, window.location.origin).href;
    }