Using Prettier with Astro

TechPrettierAstroWeb

Creating a website can be quite easy. Using a framework usually helps. However, using many frameworks with different styles will result in chaos. Every file brings its own indentation and nothing really matches. Luckily, there is Prettier. Prettier is a code formatter which can be installed as a dependency and then used to simply unify the style/format of your code. I will not elaborate why a unified code style within a project is beneficial but it generally is.

So, I added Prettier to this project hoping to clean up all the mess and all this chaos but I soon had to realize that half of the project was not formatted correctly. After a quick analysis, it was obvious to me that Prettier did format all files it was familiar with but of course, .astro files are not. Luckily again, the guys from Astro already recognized this and created a Prettier plugin for .astro files.

So, I added the plugin as well and it did not work. Some minutes later, I found out, that the error ParseError: (0 , import__2.default) is not a function only appears in .astro files which use JavaScript expressions like map or forEach. Turns out, the plugin itself is currently still in Beta and updating it to the latest version yarn add prettier-plugin-astro@next fixed the problem. Now, Prettier is taking care of my code style and everything is unified!

By the way, do not run Prettier manually, add it as a Git pre-commit hook and it will format your code before each commit. Automagically.