withastro / astro

The web framework for content-driven websites. ⭐️ Star to support our work!
https://astro.build
Other
44.07k stars 2.29k forks source link

Astro somponent with `?raw` suffix no longer a string, previously was #11410

Open erwinheldy opened 4 days ago

erwinheldy commented 4 days ago

Astro Info

Astro                    v4.11.5
Node                     v20.15.0
System                   Linux (x64)
Package Manager          npm
Output                   static
Adapter                  none
Integrations             @astrojs/solid-js

If this issue only occurs in one browser, which browser is a problem?

No response

Describe the Bug

The Astro component import behavior has changed regarding the ?raw suffix, which previously treated the imported component as a string but now results in a function type. This inconsistency is illustrated by the following code snippet:

import Button from '../components/Button.astro?raw'
console.log(typeof Button) // Output: "function" (expected: "string")

Previously, the typeof Button would return string, but now it returns function, which is unexpected behavior and may impact existing code relying on the previous string type behavior. I forgot which version still resulted in a string.

What's the expected result?

The expected result is that typeof Button should return string when importing an Astro component with the ?raw suffix, as it did in previous versions where this behavior was consistent.

Link to Minimal Reproducible Example

https://stackblitz.com/edit/github-4mfaty?file=src%2Fpages%2Findex.astro

Participation

ematipico commented 4 days ago

Is this documented anywhere @erwinheldy ?

Princesseuh commented 4 days ago

It's a Vite thing: https://vitejs.dev/guide/assets.html#importing-asset-as-string, we have a few part of the docs either directly recommending the pattern, or linking to their docs. We also recommend it once in a while to people in support.

It's a common pattern for component library documentation, so they can show both the component and its source code without duplication

erwinheldy commented 4 days ago

Yes, indeed, it's a Vite thing as mentioned by @Princesseuh.

e3stpavel commented 2 hours ago

I found out that if you try to render the imported Astro component with ?raw the output is the source string.

Given the following example:

---
import { RawComponent } from './components/Component.astro?raw'
---

<RawComponent /> {/* this will output `component.astro` source code */}

Therefore, if this is the expected behavior, it is worth changing the type definition of *.astro?raw in astro/client.

@erwinheldy With that in mind you can utilize slots or newly added Container API to render the component and get the source string.