#using a string path for images stored in src

1 messages · Page 1 of 1 (latest)

hollow cipherBOT
#

Hi @royal moth. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

No, you should not use a string path like "../assets/images/portfolio/port1.jpg" to reference images stored in your src directory when using Astro. According to the Astro documentation, for images in src/, you must import them using ESM import statements. Using a string file path for images in src/ will not work as expected and will not be processed or optimized by Astro. This applies to both the <Image /> and <Picture /> components, as well as when using native HTML <img> tags if you want the correct build output.

Correct usage:

---
// Import the image from src
import port1 from '../assets/images/portfolio/port1.jpg';
import port1m from '../assets/images/portfolio/port1-m.jpg';
---
<picture class="cs-picture cs-picture1">
  <source media="(max-width: 600px)" srcset={port1m.src} />
  <source media="(min-width: 601px)" srcset={port1.src} />
  <img aria-hidden="true" decoding="async" src={port1.src} alt="new hallway" loading="lazy" width="400" height="560" />
</picture>

If you use a string path, Astro will not be able to resolve or optimize the image, and you may encounter build errors or broken images. The documentation explicitly states that the src parameter must be an imported image or a URL, not a string file path for local images in src/ Local images must be imported Display unprocessed images with the HTML <img> tag.

#

Summary:

  • For images in src/, always import them and use the imported object’s .src property in your markup.
  • String paths only work for images in the public/ directory or for remote URLs.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: