Reformat Your JavaScript Code with Prettier: 10 Easy Steps

Introduction

Maintaining clean, readable, and consistent code isn’t just a good practice, but within a large project it’s necessary.  Javascript and Typescript are pretty flexible with stylistic rules, so having a guideline or formatter is important to keep everything on the same page.  This is where Prettier comes into play.  In this guide we’ll go over how you can seamlessly reformat your Javascript or Typescript codebase using Prettier.  This will not only keep your code up to date with industry standards, but also enhance team collaboration, make MRs easier to review, and improve your overall code quality.

What is Prettier

Prettier is more than just a tool; it’s a path to coding harmony. As an opinionated code formatter, it enforces a consistent style by parsing your code and reprinting it with its own rules, taking the guesswork out of code formatting. This means line lengths, spacing, and other stylistic concerns are automatically handled, allowing developers to focus on what matters most: writing quality code. With Prettier, you bid farewell to code style arguments and welcome a more streamlined, efficient coding process.

Should I be using a code formatter?

There are pros and cons to using a code formatter, but in general they are recommended for large projects. In the fast-paced world of development, a code formatter is not just a luxury; it’s a vital tool. It ensures consistency across your codebase, making it easier to read, maintain, and debug. Whether you’re a solo developer or part of a larger team, a code formatter like Prettier can revolutionize your coding workflow, leading to more efficient and error-free development.

How to reformat your codebase with Prettier

1) Install Prettier

Most IDEs have prettier configured in either an extension or plugin, but this step is recommended by prettier so your app and IDE versions don’t mismatch.  To do this you can run the following command in your terminal at the root of your project:

PowerShell
yarn add --dev --exact prettier

# or

npm install --save-dev --save-exact prettier

2) Create Config Files

Prettier uses Lilconfig syntax for it’s configuration preferences, to make things easy we just created a .prettierrc file that has any custom style overwrites. For the most part the base style is recommended and is a good standard for most companies.  Our team decided on the following .prettierrc file.

JSON5
{
    printWidth: 100,
    tabWidth:4,
}

Create a .prettierignore file. This will stop prettier from automatically reformatting files that you don’t want reformatted. For example:

# .prettierignore
# Ignore artifacts:
build
coverage

# Ignore all HTML files:
**/*.html

You can also ignore individual lines within your project by adding a comment above a line like so:

JavaScript
// prettier-ignore
const myUglyLine = [1,
2,3, 4,5
6]

// what it would be changed to if we didn't have the comment 
const myPrettyLine = [1, 2, 3, 4, 5, 6, 7, 8]

3) Configure your IDE

Most Ides have an extension for prettier that has different installation options.  Each code editor will be different, check here for yours specifically.

In the case of VSCode, there is a default formatter option that you can search for in settings to ensure that it’s not defaulting to anything else.  One other option you should find to enable is to format on save.  This is useful for debugging code that may have misindentations and brackets, along with letting you worry about coding and not what the code looks like. 

Each user will have to do this if they want their ide to use the prettier settings, if they like their own coding style we can set this to be a pre-commit hook in our projects settings which we will explain later

4) Run the Debug Check

If you’re doing a big refactor it can be good to become familiar with some of the CLI commands.  When reformatting a bunch of files you want to ensure that no errors come about from reformatting.  Luckily prettier has a debug flag that can check if running the reformat might change the logic of the code. 

For example in this stack overflow forum,  this line of code was conflicting with the prettier style

JavaScript
const conflictingLine = (a && a.length > 0) && (b && b.length > 0); 
// debug check broke on this line, parentheses aren't needed here so removing them fixed the conflict
const fixedLine = a && a.length > 0 && b && b.length > 0;

After running the debug-check on all of the files that you plan on reformatting, take a screenshot or copy that list so we can go through and manually fix those files.

5) Fix Debug Conflicts

Once you find a file that might throw an error, you need to figure out where it’s happening in that file.  I found that SO link from the last step because I was trying to find what in my file was conflicting with Prettier.   If you’re good with git and changelogs you could make a backup then change those files and look. 

Otherwise if you’re like me and didn’t think of that at the time you can comment out different blocks of the code then run the debug check on those individual files and see where it passes and where it fails. Unfortunately the debug check doesn’t give very verbose conflicts at the moment.

Once all your debug check conflicts are resolved we’re ready to make the all mighty commit. 

6) Update your Lint Config and Pre-commit hook

If you don’t have a linter or pre-commit hook you can skip this step, but if you do, you’ll probably want to ensure that it doesn’t have any styling conflicts with prettier.  Remember that prettier is a code formatter and styler, where the linter should have more code quality type rules.  To do this check the docs here

If you have a pre-commit hook it can be useful to put prettier into that, so each commit automatically gets formatted even if the individual user decides to use that format or not.  This way you can ensure that all the files going into the codebase have the properly formatted code.  Since pre-commit hooks can vary, check out here for yours in particular.

7) Run the Royal Commit

To make sure this is all working with the pre commit hooks, you can try to make a commit and see if the file auto reformats.  If it does, congrats! The hardest part is over.  If it doesn’t, double check your pre-commit hook settings and how they should integrate with Prettier.

If you’re not using pre-commit hooks you can go ahead and run the –write cli command on your folder instead of the debug-check. 

8) Create a .git-blame-ignore-revs-file

If you’re using git and like to see the blame history on each line, be sure to create this file so that all the files that get changed in the commit don’t have your name on them.  Create an empty file then copy and paste your commit hash into the file.  An example of the file shown below  

# .git-blame-ignore-revs

# Reformatted codebase
21d0948yt234gjnv823497nvn83n499259vnv2345

# Any other commit to ignore the blame for 
ggj25h6431jnklnh2p4jk5nph2p4oikj5hnpv2p9s

I did a bit of research on the best way to keep the original blame history, and came across git blame someone else as a joke package.  I thought we could maybe put ‘The Great Reformat of 2023’ as the author of any changes, but modifying git isn’t recommended, and keeping the original history works out better.

Just having this file in the code base should ignore blame for the online github and gitlab editors, but we now need to enforce this on our personal IDE.

9) Enforce the ignore-revs file

Now that the .git-blame-ignore-revs file is in the code base, once you and your teammates pull you’ll have to configure git and the IDE to use that ignore file.  There are a few ways to do this, but we did it in our local git config with the command:

git config blame.ignoreRevsFile .git-blame-ignore-revs

Now git should properly ignore those commits, it also might be a good idea to throw this in your .README for any new users that decide to start developin.

*Note that if the git annotate or blame in your IDE isn’t showing the correct original commits, try to restart your IDE or disable/uninstall and reenable or reinstall any git or git related IDE extensions.  That fixed some of the blame issues for users on our team.  

10) Enjoy Your Newly Formatted Codebase!

I hope you notice an improvement in code quality and the speed of which you write code since you don’t have to worry about how things have to be styled. Then moving forward the team should all be pushing normally styled code into the codebase, whether or not the individual user decides to use the formatting in development or not.  Obviously meet with your peers to find the right options and explain how prettier works, but now you’ve joined the dark side.

If this helped or you have any comments, questions or concerns feel free to drop a comment below.  As always, happy coding!

Leave a Comment

Your email address will not be published. Required fields are marked *