Skip to main content

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:

  Link 1
  Link 2

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:

{ => {
  return (
      aria-current={Astro.url.pathname === item.url ? "page" : null}

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:

{ => {
  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.

About the author

Sean McPherson is a software engineer for Khan Academy who specializes in web development. He lives with his wife, sons, and dog in Pittsburgh, PA.