Format Astro files in VS Code with Prettier

By

Learn how to auto-format .astro files in VS Code with Prettier by installing prettier-plugin-astro and enabling Format On Save and Format On Paste.

~~~

To auto-format .astro files in VS Code you install the prettier-plugin-astro plugin in your project, then enable Format On Save. Prettier alone can’t do it.

One downside of using Astro is that Prettier does not understand its syntax.

An .astro file mixes a JavaScript frontmatter block, HTML, and JSX-like expressions. Prettier only ships formatters for the languages it knows, and Astro is not one of them.

So auto-formatting on Save/Paste does not work in VS Code out of the box.

How can you automatically format Astro files in VS Code using Prettier?

To make it work we need to do some configuration.

Install the plugin

First install the default formatter for Web Development, which is Prettier. In VS Code, that’s the “Prettier - Code formatter” extension.

Prettier does not have a specific formatter for Astro.

So inside your project folder, install this plugin https://github.com/withastro/prettier-plugin-astro by running

npm install -D prettier prettier-plugin-astro

I install prettier locally too, so the plugin and Prettier versions stay in sync inside the project.

With Prettier version 3 and newer, plugins are not picked up automatically anymore. You have to list the plugin in your Prettier config. Create a .prettierrc file in the project root:

{
  "plugins": ["prettier-plugin-astro"]
}

Configure VS Code

Now make sure in the VS Code settings you have enabled Editor: Format On Save and Editor: Format On Paste.

Then when you save the file or paste code you should see it being formatted.

If VS Code picks another formatter for .astro files (the Astro extension registers one too), tell it to use Prettier. Add this to your settings.json:

"[astro]": {
  "editor.defaultFormatter": "esbenp.prettier-vscode"
}

Still not formatting?

If it doesn’t work, make sure in VS Code you opened the specific project folder.

Not the project’s parent folder.

This might make the Astro formatter not work, because the Prettier extension looks for the plugin in the workspace’s node_modules, and it won’t find it one level up.

Another quick check: run Prettier from the terminal to see if the setup itself works:

npx prettier --write src/pages/index.astro

If this command formats the file but VS Code doesn’t, the problem is in the editor settings. If the command fails too, the plugin isn’t installed or isn’t listed in .prettierrc.

Once everything is wired up, formatting works on the whole project as well, which is handy before a commit:

npx prettier --write "src/**/*.astro"
Tagged: Tools · All topics
~~~

Related posts about tools: