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

Formatting can break syntax when using Typescript

Open scoopandrun opened this issue 2 years ago • 2 comments

When writing Typescript code in the "HTML" (or "body") part of a Svelte component, I came across a formatting issue that broke the syntax of the code.

The code in question follows below.
I duplicated the line in the script tag and the "body" part to show that the two parts behave differently. The first code block is before formatting; the second is after formatting.

Before formatting:

<script lang="ts">
  Array.from<Element>(document.querySelectorAll("textarea")).includes(document.activeElement);
</script>

{Array.from<Element>(document.querySelectorAll("textarea")).includes(document.activeElement)}

After formatting:

<script lang="ts">
  Array.from<Element>(document.querySelectorAll("textarea")).includes(
    document.activeElement
  );
</script>

{Array.from <
  Element >
  document.querySelectorAll("textarea").includes(document.activeElement)}

As you can see in the "body" part of the component, from<Element>( became seriously modified with spaces and line breaks where there shouldn't be and syntax highlighting being lost (in VS Code).
Furthermore, the formatting operation removed some parentheses (initially surrounding document.querySelectorAll("textarea")), thus breaking the code syntax.

The <script> part is correctly formatted without breaking anything.

I tried the same line in a .ts file (with only this line), formatted with Prettier and everything went well (just as in the <script> tag above). So I think this is an issue with this plugin, not with Prettier.

Interestingly, I tried with shorter lines to see if that could resolve the issue, but it didn't. Here are the results:

Before formatting:

<script lang="ts">
  let a: Element;

  Array.from<Element>(document.querySelectorAll("*")).includes(a);
</script>

{Array.from<Element>(document.querySelectorAll("*")).includes(a)}

After formatting:

<script lang="ts">
  let a: Element;

  Array.from<Element>(document.querySelectorAll("*")).includes(a);
</script>

{Array.from < Element > document.querySelectorAll("*").includes(a)}

Here again, in the "body" part, spaces around the type Element and parentheses removed in the following part of the code.
And the <script> tag is correctly formatted.

scoopandrun avatar Mar 09 '23 21:03 scoopandrun

I just realized that apparently you can't use Typescript at all in curly braces in the "body" part of a component code, even if the script tag is <script lang="ts">.

scoopandrun avatar Mar 09 '23 21:03 scoopandrun

Blocked by https://github.com/sveltejs/svelte/issues/4701

dummdidumm avatar Mar 14 '23 10:03 dummdidumm