seanmcp.com

Fix trailing whitespace in Astro components

When your Astro code is formatted onto multiple lines, the resulting markup from the Astro compiler includes a whitespace. This is noticeable when you have a list of links that are underlined:

<a>
  Link 1
</a>
<a>
  Link 2
</a>

Result: Link 1    Link 2

But if the markup is on a single line, then the issue goes away:

<a>Link 1</a>
<a>Link 2</a>

Result: Link 1   Link 2

I have faked the output for this article, but you can see a live reproduction of this behavior on StackBlitz.

To workaround this issue, you need force your markup onto a single line. Let’s look at a real-world example element with multiple attributes. Your code formatter will spread it over multiple lines:

{items.map(item => {
  return (
    <a
      aria-current={Astro.url.pathname === item.url ? "page" : null}
      href={item.url}
    >
      {item.label}
    </a>
  )
})

To force this code onto a single line, we need to refactor. Create variables to represent attributes and children with short names, and then pass them to the element:

{items.map(item => {
  const a = {
    'aria-current': Astro.url.pathname === item.url ? "page" : null,
    href: item.url
  }
  const c = item.label
  return <a {...a}>{c}</a>
})

This code is objectively worse (and might create a TypeScript warning that you need to ignore), but it will fix the whitespace issue. Hopefully the Astro team can fix the issue in the compiler and make this workaround unnecessary.

Reply by email Romans 5:8