prettier-plugin-astro icon indicating copy to clipboard operation
prettier-plugin-astro copied to clipboard

🐛 BUG: Plugin does not handle script tags inside expressions correctly

Open GabeDuarteM opened this issue 2 years ago • 6 comments

Describe the Bug

If I have the following file:

---
---

<!DOCTYPE html>
<html lang="en">
  <head>
    {true && <script>const thing = { age: 1 }</script>}
  </head>
  <body>
  </body>
</html>

when I run prettier --check --plugin-search-dir=. ., I get this error:

Checking formatting...
src/layouts/Layout.astro[error] src/layouts/Layout.astro: SyntaxError: Unexpected token, expected "}" (1:39)
[error] > 1 | <>{true && <script>const thing = { age: 1 }</script>
[error]     |                                       ^
[error]   2 | }</>
All matched files use Prettier code style!

Just for some context, I have that conditional script so I only write it to the tom if an environment variable is present, and inside it I need to create an object.

My guess is that prettier is probably not correctly applying the javascript context inside the script tag when there is this conditional check. It does work as expected if I remove the {true && part, leaving only the script tag

Steps to Reproduce

  1. npm init astro using the default template
  2. edit Layout.astro to have the following:
---
---

<!DOCTYPE html>
<html lang="en">
  <head>
    {true && <script>const thing = { age: 1 }</script>}
  </head>
  <body>
  </body>
</html>
  1. run prettier --check --plugin-search-dir=. . to check all files with prettier
  2. Check the error on the console:
Checking formatting...
[warn] astro.config.mjs
[warn] package.json
[warn] README.md
[warn] src/components/Card.astro
src/layouts/Layout.astro[error] src/layouts/Layout.astro: SyntaxError: Unexpected token, expected "}" (1:39)
[error] > 1 | <>{true && <script>const thing = { age: 1 }</script>
[error]     |                                       ^
[error]   2 | }</>
[warn] src/pages/index.astro
[warn] tsconfig.json
[warn] Code style issues found in the above file(s). Forgot to run Prettier?

Might be related to #335

GabeDuarteM avatar Mar 26 '23 03:03 GabeDuarteM

Hmm, that one might be a bit challenging. I think it's caused by Prettier's JSX parser not understanding script tags.

The issue you posted is unrelated, though. No worries there

Princesseuh avatar Mar 26 '23 21:03 Princesseuh

Would you like to try dprint with markup_fmt? markup_fmt can correctly format <script> tags in Astro expressions.

g-plane avatar Mar 06 '24 02:03 g-plane

I have the same issue: image Does somenone work on that bug?

spolarRASP avatar Mar 22 '24 11:03 spolarRASP

@spolarRASP Try markup_fmt.

g-plane avatar Mar 22 '24 12:03 g-plane

is there a way to add a prettier-ignore comment to silence that error?

stefanprobst avatar Mar 30 '24 06:03 stefanprobst