Last updated: 2019-5-13
What is Prettier?
One of the things I love about it is it’s not completely rigid with its rules. It makes some “logical” choices that I would make myself. For instance, Prettier will make a short const array declaration a one liner, but a declaration with a bunch of items in the array, it will split out into multiple lines to avoid horizontal scrolling (see demo GIF at the end). I love that.
VS Code Integration
Note: Make sure you have prettier installed in the project you’re working in or globally via
npm install prettier -g
Format on Save in VS Code
To enable Format on Save in VS Code:
- Search for Format On Save and check the box
Overriding Prettier settings
By default Prettier uses 2 spaces for your tab width for indenting your code. You can increase that to the VS Code default of 4 if you want extremely easily.
- Add a
.prettierrcfile in the root of your project next to your package.json
- Add a new object with a
tabWidthproperty and a value of
- Note how VS Code gives autocompletion for the different settings within Prettier. How awesome is that!?!
- Now start saving your files and watch Prettier in action.
Note: you can configure these settings directly in VS Code as well without a config file, but I think it’s better to use a .prettierrc file, especially when you’re on a team. That way anytime you or someone else works on that codebase, everyone is using the same settings.
The rest of the Prettier configuration options can be found here.
Formatting is something I never worry about anymore
I find when using Prettier, along with the Format On Save option in VS Code, I don’t think about how to format my code anymore. I don’t ever wonder “oh should I put this on multiple lines or keep it all in one line?” Instead, I focus on solving my problem, hit Save and let Prettier do the rest. It’s shocking how liberating this is. I end up with consistent formatting across my entire project instead of just doing whatever I felt was best at the time.
Prettier in Action