lilnasy / gratelets

A collection of purpose-built, small, third-party integrations for Astro.
The Unlicense
111 stars 6 forks source link

Cannot use stylex in `.astro` files #99

Open Haberkamp opened 6 months ago

Haberkamp commented 6 months ago

Hi, it's not possible to use stylex in astro files. I can only use it in react components.

---
import * as stylex from '@stylexjs/stylex';

const styles = stylex.create({
  foo: {
    color: "red"
  }
});
---

<p {...stylex.attrs(styles.foo)}>lorem</p>

This is the error I get: stylex.create() is only allowed at the root of a program.

lilnasy commented 6 months ago

This happens because the frontmatter in .astro files, after compilation, is not the "root". This compilation is similar to svelte's, and I have described the caveat of using stylex alongside svelte here: https://github.com/lilnasy/gratelets/tree/main/packages/stylex#svelte.

To summarise, Stylex needs the styles to be written at the top-level, not in the body of a function. Astro compiles the frontmatter into a body of a function.

Astro has an undocumented escape hatch, however: you can write an exported const declaration instead of a const declaration. For example,

+export const styles = stylex.create({
-const styles = stylex.create({

This will make astro compile the stylex.create() line onto the top-level or "root" of the module, instead of compiling it into the body of the function.