#Different output in dev and build

5 messages · Page 1 of 1 (latest)

verbal vector
#

Is there a way to render a component differently in development and the build?

I have a YouTubeVid component like so:

---
interface Props {
    id: string,
}

const { id } = Astro.props;
---

<div>
    <iframe width="560" height="315" src={"https://www.youtube.com/embed/" + id} title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div>

Right now, it renders as a video embed. I want it to render as a simple video link in development and an embed in the build.

worthy orbitBOT
#

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

#

To render a component differently in development and production builds in Astro, you can use the import.meta.env.PROD environment variable. This variable is true when running in production mode and false in development mode. Here's how you can modify your YouTubeVid component to achieve the desired behavior:

---
interface Props {
    id: string,
}

const { id } = Astro.props;
const isProd = import.meta.env.PROD;
---

{isProd ? (
  <div>
    <iframe 
      width="560" 
      height="315" 
      src={`<https://www.youtube.com/embed/${id}`}> 
      title="YouTube video player" 
      allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" 
      referrerpolicy="strict-origin-when-cross-origin" 
      allowfullscreen
    ></iframe>
  </div>
) : (
  <a href={`<https://www.youtube.com/watch?v=${id}`}>Watch> on YouTube</a>
)}

In this modified version:

  1. We import the PROD environment variable using import.meta.env.PROD.
  2. We use a conditional rendering based on isProd.
  3. In production (isProd is true), it renders the iframe embed as before.
  4. In development (isProd is false), it renders a simple link to the YouTube video.

This approach uses Astro's built-in environment variables, as described in the Using environment variables guide. The import.meta.env.PROD variable is one of the default environment variables provided by Astro.

Remember that this difference will be visible when you run astro dev (development mode) versus when you run astro build and serve the built files (production mode).

#

@verbal vector Kapa.ai is still learning and improving, please let me know how I did by reacting below.