DEV Community

loading...
Cover image for Adding Prettier to a Project

Adding Prettier to a Project

Sia Karamalegos
Front-end developer passionate about web performance, international conference speaker and Google Developers Expert
Originally published at sia.codes Updated on ・2 min read

While working at a smaller dev shop, our team hit the point at which the inconsistent code formats between and within projects was becoming a pain. Our needs included:

  1. A consistent linter/formatter for all projects in a particular language
  2. An autoformatter so developers didn't spend time "fixing" linter errors
  3. A tool readily available in tools like VS Code which could apply changes on save

We decided to go with Prettier. We also added a pre-commit hook to ensure that all code changes complied with the new authoritarianism.

I initially published this as a gist to help when setting up new projects at that company. Today, it was useful for a client I was working with, so I'm sharing it now in an article in case the same use case fits for you, and you'd like a handy reference.

The Steps

Most of these steps can be found in the docs and through other links in the docs.

A key step here is to run Prettier on all the files in a separate commit. You don't want to pollute all your future pull request diffs with formatting changes.

(1) Install prettier:

$ npm install --save-dev --save-exact prettier
Enter fullscreen mode Exit fullscreen mode

(2) Create an empty config file to let tools know you're using Prettier:

$ echo {}> .prettierrc.json
Enter fullscreen mode Exit fullscreen mode

(3) Create a .prettierignore file to let tools know which files NOT to format. node_modules are ignored by default. Some suggestions:

build
coverage
.package-lock.json
*.min.*
Enter fullscreen mode Exit fullscreen mode

(4) Manually run Prettier to re-format all the files in the project:

$ npx prettier --write .
Enter fullscreen mode Exit fullscreen mode

(5) Set up your code editor to auto-format on save for ease of use. See instructions for various editors.

(6) Set up commit hooks with pretty-quick and husky. First, install them as dev dependencies:

$ npm i --save-dev pretty-quick husky
Enter fullscreen mode Exit fullscreen mode

(7) Finally, add the pre-commit instructions to your package.json file:

"husky": {
  "hooks": {
    "pre-commit": "pretty-quick --staged"
  }
},
Enter fullscreen mode Exit fullscreen mode

Now when you commit your changes, files in the commit will automatically be formatted!

This article was originally published on sia.codes. Head over there if you like this post and want to read others like it, or sign up for my newsletter to be notified of new posts!

Discussion (21)

Collapse
jonrandy profile image
Jon Randy

Personally cannot stand what Prettier does to my code. Avoid

Collapse
piotrlewandowski profile image
Piotr Lewandowski

Prettier does whatever you ask it to do. If you hate the result, change the prettier configuration to your liking. Tools like prettier suppose to help with consistent formatting of the source code (especially useful when working on codebase with multiple devs). It works especially great when combined with some linting tool (ESLint).

Collapse
jonrandy profile image
Jon Randy

I've tried everything I can to make it not wreck the way I format my code. No go

Thread Thread
piotrlewandowski profile image
Piotr Lewandowski • Edited

Did you try to combine prettier and ESLint? (eslint-plugin-prettier). Unless you have very, very unusual way of formatting you code it should really help...
I could help with configuration if you'd be able to publish your prettier/eslint config (on gist maybe?)
edit: here's my Webpack 5 boilerplate with ESLint/prettier config, maybe it'll help: github.com/piotrlewandowski/webpac...

Collapse
psiho profile image
Mirko Vukušić • Edited

Agree. And its far from configurable. It's very opinionated. I really developed a deep hate about prettier code :)

Collapse
piotrlewandowski profile image
Piotr Lewandowski

What you really did is developed deep hate about YOUR configuration of prettier (or lack thereof)... It does exactly what you ask it to do: format the code the way you asked it to do.

Thread Thread
michaellouviere profile image
Mike Louviere

Exactly.

Developer: "I setup Prettier and I hate it"
Me: "Well, did you configure it the way you'd like"?
Developer: "..."

The reality is, I'd rather have consistent line breaks, quotation types, semi-colons etc across a project. It's particularly helpful when working on teams. It seems a lot of the people I hear who complain about it are developers working on solo projects or developers who want to write inconsistent code.

Thread Thread
psiho profile image
Mirko Vukušić • Edited

It's not true that it can do whatever u want. There is a reason it's webpage clearly states that it is opinionated. Even if it wasn't, there simply is no way to cover all the options with config.

It's just a compromise between big/bad team consistency issues and uglyness of the code (which is highly subjective). The bigger and the worse team is, more you're forced to swallow downsides of autoformatted code.

But let's stop calling it the ONLY option, and the BETTER OUTPUT than what u can do manually. Come on, it's just an ugly compromise, a "necessary bad" sometimes.

Thread Thread
michaellouviere profile image
Mike Louviere

Who called it the "ONLY" option?

Thread Thread
psiho profile image
Mirko Vukušić

It's written between the lines all the way. Just like it's written between my lines all the way that I'm not talking about Prettier but about any opinionated code autoformatter

Thread Thread
michaellouviere profile image
Mike Louviere

Your tone is a bit off putting. But I don't think anyone claimed Prettier is the "ONLY" option. If you have better options or concepts for this sort of thing, I'm pretty sure anyone reading these comments would love to hear them. I would never claim Prettier is perfect, or the only/best option, or even the right option for everyone.

Tools are just tools, it's how you leverage them that provides value. I never go all-in on technology or tools, if there's something better then I'm always open to hearing/learning.

Thread Thread
psiho profile image
Mirko Vukušić • Edited

Again, it's not Pretier thats not the only option... It's opinionated autoformatters altogether. And it was not the comment on the post (wrote completely different thing there), but was a comment on the comment which was also highly opinionated. In that context, I completly stand by it, and think it's completely proper thing to state.

As for the arcle itself, as a suggestion can only add stuff like: educating the team, code reviews, pair programming, internal discussions about the standards (instead of pushing it top-down) and simple Eslint or langserver autofixers.

Thread Thread
andreidascalu profile image
Andrei Dascalu

I'm not sure if you actually read anything in the article. It's an article about setting up Prettier. It may come as a shock, but if an article is about X, there's no obligation to also include Y, Z, T. It's not a versus, top10 or anything else. Prettier isn't the only option, it's the option that happens to be the subject of this particular article. Deal with it.
Highly opinionated is good. Choice for the sake of choice is stupid. As developers we have plenty of things to educate the team about or discuss at reviews. Design patterns, architecture, security, libraries, etc. Time spent on education on why to use tabs instead of spaces or single vs double quotes depending on context is pointless. There will be developers coming into the company or moving inside and the last thing you need is time wasted on reconfiguring IDE's to match the policies of that project. You use git hooks or not, autoformat on save or not, how do you format? Do you use tabs or spaces and which tab size? 2, 4 ... 6?
Thing is, everyone is opinionated. It's just that not everyone's opinion align and there's absolutely no objective reason (regarding formatting) to take one opinion over another, so that's why there are tools that are enforcing community drive standards - for no other reason that a bunch of people came together and agreed on something, which doesn't happen very often on projects.

Thread Thread
jonrandy profile image
Jon Randy

Tabs

Thread Thread
andreidascalu profile image
Andrei Dascalu

We should all be free to use x's for indentation and suffix each line with an ASCII dragon.

Thread Thread
psiho profile image
Mirko Vukušić • Edited

@andreidascalu , i think you're the one not reading. Read the thread. It was not the comment on the article. It all started with someone else suggesting to avoid Prettier altogether and me writing a short line that i second that. Only to be attacked with highly subjective, opinionated and also incorrect statements (i.e. that only single-team devs are against Prettier or the ones that dont want to write clean code, that Prettier can be configured any way you want, etc).

Now you pull that all out of context and think that was an article comment, while it was only a reply on another comment. Byt you still manage to add incorrect and misleading info, like mentioning tabs vs spaces, quotes, etc. It's exactly the aura arround Prettier, that it is often forcefully applied at many places just because "everybody does it" without really understanding the thing. Again an example from your post... Tabs!? You really think Prettier saved us from tabs inconsistencies in the past? Having to reconfigure editors? You really think all of us not using Prettier are forced to reconfigure editors?? Never heard of ESlint? Editorconfig? Point is, for some newbie reading this article, they might think those that dont use Prettier just have a mess of code, reconfigure editors all the time, have mixed tabs and spaces, etc. It's rediculous, doesnt help educate anybody and is simply incorrect.

And btw I use Prettier, when I have to. It's justa a tool, usefull in some circumstances, depending on the size and the quality of the team. Article was about small company "just reaching the point where inconsistency became a problem". So it's a very good comment/advice to look alsewhere!

Those holy wars and personal attacks about softeare tools are just rediculus. I just don't understand how is it possible to have such an emotianla reaction if somebody dislikes the tool you use?

Thread Thread
andreidascalu profile image
Andrei Dascalu

" I just don't understand how is it possible to have such an emotianla reaction" - well, you should look at yourself. There's an article on how to setup a tool you don't use/like and feel the need to attack the tool & the people using it. The sane thing is to move on or just write a reaction post about your setup and why that's better. An article on how to setup X (not why X is great, X vs others, etc) doesn't need to mention what you think it should.
I'm also glad that you fixated on my sarcasm about tabs. Definitely too subtle for you.
The point isn't that Prettier itself is a great tool, it's that opinionated formatters are great because they take away the debate. Just look at your own points: Prettier doesn't conform to how YOU want YOUR code to look like (on which you can already see why some might think that Prettier-haters are lone devs) not that it breaks some community-promoted coding standards (which it doesn't, even at defaults). On top of that you're worried that this particular article (out of the sea of articles on this platform about code formatting) might give some newbie the idea that Prettier is the only tool out there (horrifying) - which says more about you than some potential newbie who happens to hit this article as the top Google result and somehow decides to stop looking.
If a newbie has no idea about code formatting and happens to stumble into Prettier and decides to use it (though clearly it's a lone dev, because as part of a team a newbie would definitely not get the last word on project setup), why is that an issue? It solves a problem, it has sane defaults (even if YOU don't happen to like it), it covers multiple languages (so you can cover the full stack, not just JS) and it's easier to configure (sure, editorconfig is even easier, but only deals with very basic generic editor formatting rules, not language-specifics).
This comment thread is the very reason why I love opinionated tools - there's absolutely too much debate (and obviously emotion) about code formatting. Way more than the subject deserves.

Thread Thread
psiho profile image
Mirko Vukušić

Youre just not reading at all. Me atacking people using Prettier?! Where? Can you quote me? Im pretty sure Im just replying to people who attack me for not using it or saying anything agains it.

But you just keep repeating the same stuff over and over again. Except one thing... Why is it not ok to comment on article about XYZ setup and state that there are better alternatives sometimes? Are there any community or moral standards about it? If comments like this were not allowed on dev.to I'm pretty sure I wouldn't read it at all. What is the point of single-sided views of any article and censorship on comments that disageree?

Then again you relate my comments to article excluaively while I told like 3 times to read the thread and the context. Article will not paint that picture I mentioned to a newbee! Comments I replied to, including yours, will.

Last thing Ill try to correct one more time is this long talk about Prettier benefits. I agree with every single one of them, and because of some of them, I use Prettier sometimes. But your view on it is single-sided and mentions no downsides, ever! Like it is a no brainer and universally better. And if anybody disagrees youre there to correct it and name them single devs or the ones that don't care about the formatting. It like religion.
But in reality it has compromises like anything else and you should waight pros and contras for each different implementation/situation. Prettier is far from universaly accepted as a standard, forums about it are far from peaceful, it is completely incorrect to say it can be configured any way u want, etc. Nothing like your comments (and some other) describe it. It's a compromise which is sometimes not worth it compared to other methods, and sometimes is worth it. So stop blaming it on devs or their setup exclusively, if they dont like it.

Thread Thread
piotrlewandowski profile image
Piotr Lewandowski • Edited

Oh dear, that escalated quickly.... Small hint for you guys: if you cannot discuss things in internet in polite manner take some offline hobby instead, I don't know, grow carrots, or something? :) And come back here only when you grow up? :)
And RTFM: dev.to/code-of-conduct

Thread Thread
psiho profile image
Mirko Vukušić

@piotrlewandowski , I did that very, very long time ago. Might say the same, but it would be personal insult and is not my style. I admit to be passionate in discussions, as any average Mediterranean is, but not personal. Closest to that I came was saying "you don't read" after being acused for the same. On the other hand, I was treated with stuff like "solo dev", not wanting to write consistent code, being to shallow to get sarcasm,... and now to be a kid that needs to grow up.

Enough said in this thread. For the sake of the few reading this long thread,... Why/when not Prettier? If you have small enough team and are willing to setup your own formatting standards you can agree on them and implement them with tools like Eslint or your langserver: autofix formatting, do it on save, require it on commit, etc. You may spend more time configuring but decissions about formatting standards will not be taken away from your team and almost the same consistency can be achieved. In example, if you want to allow matrix style layout for props/params sometimes, or 'hide' some repeating long lines of code to avoid scrolling down to more important stuff, etc... you might find that Prettier code is not allways prettier nor more efficient to manage. The bigger your team is, or more diversified, ... opinionated formatters will be more usable. You'll win some and loose some but in general win will be bigger.
But again, for small(er) teams, at least run some of your projects through Prettier and see if it causes more frustration than it cuts down formatting inconsistencies, compared to non-opinionated tools like Eslint.

Collapse
thegreengreek profile image
Sia Karamalegos Author

Or Dev