#define:vars undefined

3 messages · Page 1 of 1 (latest)

rancid fossil
#

Hello,
I import an image in frintmatter

import bgImage from "@images/lens-flare.jpg";

const image = bgImage.src;

Then I use it as a var in the style

<style
define:vars={{
bg: url(${image}),
}}

var(--bg)
returns undefined. why?

smoky perchBOT
#

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

#

Based on the information provided in the knowledge sources, I can explain why you're encountering this issue and suggest a solution.

The problem you're experiencing is likely due to how define:vars works with image imports in Astro v3.0. According to the Upgrade to Astro v3 guide, there have been changes to how image imports are handled.

In Astro v3.0, when you import an image, you get an image object rather than a string URL. This is why image (which is bgImage.src) is not working as expected in your define:vars.

To resolve this issue, you have two options:

  1. Use the ?url suffix when importing the image:
---
import bgImage from "@images/lens-flare.jpg?url";
const image = bgImage;
---

<style define:vars={{ bg: `url(${image})` }}>
  /* Your styles here */
</style>
  1. Access the src property of the imported image object:
---
import bgImage from "@images/lens-flare.jpg";
const image = bgImage.src;
---

<style define:vars={{ bg: `url(${image})` }}>
  /* Your styles here */
</style>

Both of these approaches should resolve the "undefined" issue you're experiencing.

Navigating Image Imports in Astro v3.0

Remember that during development, Astro uses a src/ path, but upon building, it generates hashed paths like /_astro/cat.a6737dd3.png. This behavior ensures proper asset handling in both development and production environments.

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