Skip to content

Instantly share code, notes, and snippets.

@JLarky
Last active February 13, 2024 12:18
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JLarky/b26a165d628984723fe285201ca699e5 to your computer and use it in GitHub Desktop.
Save JLarky/b26a165d628984723fe285201ca699e5 to your computer and use it in GitHub Desktop.
Use prettier formatting with Astro (pnpm)
/**
* @type {import('prettier').Options}
*/
module.exports = {
plugins: [require.resolve('prettier-plugin-astro')],
overrides: [
{
files: '**/*.astro',
options: { parser: 'astro' }
}
]
}

Prettier plugins are not auto detected when using pnpm prettier/prettier#8056

So you will get following error:

src/pages/index.astro[error] Couldn't resolve parser "astro"

So let's write down all that I had to do to make it working.

pnpm install -D prettier-plugin-astro@next # ni -D prettier-plugin-astro@next

Now in your package.json add scripts:

"fmt": "prettier --write --plugin-search-dir=. ."

Now replace .prettierrc if you had one (any non-js prettier config) with .prettierrc.js. Add overrides and plugins there:

/**
 * @type {import('prettier').Options}
 */
module.exports = {
  plugins: [require.resolve('prettier-plugin-astro')],

  overrides: [
    {
      files: '**/*.astro',
      options: { parser: 'astro' }
    }
  ]
}

Now this should work:

pnpm fmt # nr fmt

But it will still not work in VSCode, for that go to command pallete (cltr+shift+p) Preferences: Open workspace settings (JSON) and add there:

usually .vscode/settings.json

{
  "prettier.documentSelectors": ["**/*.astro"],
  "[astro]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  }
}

See also:

{
"scripts": {
"fmt": "prettier --write --plugin-search-dir=. .",
},
"devDependencies": {
"prettier": "^2.7.1",
"prettier-plugin-astro": "^0.1.0-next.5",
},
}
{
"prettier.documentSelectors": ["**/*.astro"],
"[astro]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
}
}
@jimpala
Copy link

jimpala commented Feb 13, 2024

Just a note that this still works but you'll likely need the config within .prettierrc.cjs instead of .prettierrc.js 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment