128 comments

[ 0.94 ms ] story [ 150 ms ] thread
Having an auto formatter was one of my favorite things about using go (gofmt).

We’ve been using prettier for over a year now at work and it’s been really nice not having to spend much time keeping the code neat. (Works well with typescript and react also)

It's also a great answer to dissenting opinions about code style. No more arguing about when to line break inside an 'if' statement.
Exactly. Lint and code formatters are a must with big teams - now we can concentrate on the code and not on the style.
And it’s even better than go fmt cause it breaks lines for you.

Wish all languages had this sort of thing. It really has made reviewing and editing code much more pleasant at my company.

ah a perfect chance to get some Prettier+Typescript help! I am using Prettier+Typescript+React and when I do methods within classes, Prettier adds a semicolon for me at the end of each class which `tslint` doesnt like. As far as I can tell, there is no setting for Prettier to ignore ONLY semicolons WITHIN classes, its just a blanket on or off. And its somehow not respecting tslint's semicolon preference. Any idea how to fix this?

```

class Demo extends React.Component<{}, {}> {

    someStuff() {
      // some code
    }; // prettier adds this ; for me, i have to tslint:disable-line every time
}

```

We just turn off tslint formatting rules. There isn’t really a need for them if you are using prettier.
oh. unfortunately my team lead insists on having them. thanks anyway.
tslint, while quite useful last year, still had (and has) known bugs with unused variables, missing/incorrect type assertions, and other annoyances.

Most new versions of TypeScript expand on their `strict` rules, and just enabling `strict` in your tsconfig, as well as using prettier, is arguably a more robust superset of seatbelts than tslint offered. I deleted tslint from all my TS projects several months ago and don't miss it at all.

I don't think they will add them. They are very opinionated and skeptical about adding configuration options. If there is more of those, then again everyone will try and have an opinion of their own and it will end up being like ESLint. Also that will lead to a lot of time spent on understanding the configuration file which will be a disadvantage as well since currently prettier just works!
Npm install tslint-config-prettier and add it to the extends array in tslint.json to switch tslint rules to be compatible with prettier
appreciate the tip, have an upvote
I remember reading that gofmt was one of the inspirations for prettier
Prettier has saved me hours of time in code review, reviewing others code and getting reviewed myself. It is amazing how much better feedback you get when someone isn't on the lookout for a missplaced '{'.
It's great to have reviews that do not involve discussions regarding formatting
I miss this. I'm working with embedded C and we always end up nitpicking formatting in review. Using checkpatch helps, but is there something like Prettier for C? I'm aware of the tool called indent but it seems a bit arcane.
Nice to see you here Saransh, great article as always. I've set up prettier to work on every time I hit Ctrl+S on VSCode; uncomplicates all formatting issues.
Thanks! I also have the extension installed in code.
Besides the streamlining of code review, it’s hard to overstate how much this streamlines _editing_. You can modify code so much faster if you don’t have to worry at all about formatting. Just push code around any which way, cut and paste, type some giant expression into the middle of another one. Then hit Save and move on.

And contrary to what you might expect, Prettier basically never makes stupid formatting choices. It’s incredibly nuanced.

This is what I do writing Go. gofmt comes around and cleans up my mess when I save.
This. But with Elm and elm-format :) It's a must in any language!
It's also been a wonderful recent addition to Elixir.
I have kind of stopped indenting my files while editing. I know prettier will do that when I hit save (I have it as an extension in code)
Even better if your editor auto indents. I use aggressive indent mode for Emacs and it works ok. Sluggish on large files though.
> it’s hard to overstate how much this streamlines _editing_. You can modify code so much faster if you don’t have to worry at all about formatting. Just push code around any which way, cut and paste, type some giant expression into the middle of another one. Then hit Save and move on.

If this is a new discovery for you, it sounds like you missed out on these things we used to call "IDEs" which were pretty popular more than a decade ago.

Even if true, the CLI resurgence in recent years has really out shined advances in IDE in my view
I'm not saying that CLI-based tools are bad in any way. They are awesome, especially for automation.

I'm just saying that discovering the benefits of automatic code-formatting seems like a very strange thing to do in 2018.

This has been around for a loooong, looong time now.

Can you give any examples ?
This is a screenshot of some of the formatting options provided in Visual Studio:

https://imgur.com/a/6PkSi

What on earth would prettier include to make it that much more extensive?

Just curious, does VS format files based on max length and break them if it exceeds? I have never seen a setting for that
I think the idea behind prettier is that it does not have many options.

Does VS format on the fly, or only on save ?

You don't understand how much Prettier formats your code. Your condescension is misinformed. It's not comparable to run of the mill IDE formatting.
I hate replying with an XKCD, but https://xkcd.com/1053/

The OP didn't even state they're "discovering [it] in 2018", at all. And even if they did, so what? What is the point that you're trying to make -- that you're a better developer because you knew something they didn't?

Every IDE or editor I've used has had automatic indenting, but what I hadn't experienced before Prettier is working with a formatter that can break expressions onto multiple lines. For me, that's the new thing that streamlines editing.

If that was a common feature in formatting tools more than a decade ago, then I missed it too.

(comment deleted)
Exactly. Currently I have been moving back and forth between languages and editors and when I code C# or Java I miss prettier all the time.

VS Studio and IntelliJ have some language formatting but the difference between them and prettier feels huge.

I use Visual Studio with ReSharper on a daily basis, and it automatically formats code just fine - but I've been a ReSharper user for many years now, so I'm not sure if it's VS or R# that is doing the formatting!
I miss Prettier in Python. YAPF is atrocious. Good news is some Prettier contributors (let's call em pretties) are working on Python support.
(comment deleted)
(comment deleted)
What are your gripes with yapf ? I'd like to use a formatter for my Python code; should I rather wait for something better ?
Not opiniated enough, not enough configuration in the places that matter, some formatting bugs, very slow. Try it and see, it works for some people.
My favorite thing is using long argument lists with it without a trailing comma. Similar for hardcoded np matrices.
Microsoft uses Roslyn to format code as it is committed.
We started using Prettier as a pre-commit git hook and the results have been amazing. There are developers in PRs who will not be comfortable with the eslint settings, have linting turned off or will otherwise ignore linting. Prettier just streamlines so much and you can disable the warnings in eslint that prettier handles automatically. It's insanely useful.
After using prettier with vscode recently, I have to agree, not having to think about formatting at all while editing feels fantastically freeing.
To streamline it even more use aggressive-indent-mode in emacs. Your code is indented correctly after every keystroke and you have even fewer formatting worries.
Prettier is great. It's one less thing to think about, especially in teams of people with different opinions on code formatting.

I also love just banging out code without worrying about the formatting then hitting save and having my editor run prettier automatically.

We run it on our entire codebase (https://github.com/metabase/metabase), enforced by CI.

If you decide to migrate an existing codebase to use prettier here are some steps for merging existing branches after you've enabled prettier: https://gist.github.com/tlrobinson/6cad91b1203a7d2c174824a4d...

The only downside to migrating a codebase is it messes with `git blame` etc, but it's not too hard to follow changes back to before you ran prettier.

I love metabase! I know that you're running a Clojure backend, did you ever consider a similar approach there (cljfmt or any of the other ones?)?
Prettier is such an awesome tool! The best part of it is formatting jsx code - being a mixture of xml and js code, formatting it manually is such a pain. Incidentally, the existence of prettier is also a major reason React stack is my goto choice in Ui works - although it seems prettier support for Vue is [coming](https://github.com/prettier/prettier/issues/2097)
I think the authors include people from React team and fb open source team has been innovating at scale since some time now
Yeah, all the the cool kids do prettier with husky. We do prettier with husky. New webstorm will have prettier integrated so I can throw away my external tool command for that. Well, probably if `eslint --fix` worked _properly_ (and all the plugins would implement their fix part) we would not need yet another tool, but whatever...

On the other hand my problem with modern frontend is that fifteen years ago compiling a fairly complicated desktop app and then commiting it to cvs took a couple of seconds (not that the two are related of course). Now webpack cold start is one minute, hot recompilation is between 5sec and 50sec, prepush hook tests a minute or two (and then it is still lightning fast, approx 2k tests in pure jsdom), add prettier, eslint, stylelint, ticket id check to precommit hook and then boom.

We tried to turn stuff off in feature branches, but it seemed to be a bad idea... also note that we're a mixed environment with win, osx, and linux machines and on windows webpack/mocha watchers tend to lock some files randomly, so there is a good chance that someone will choke on a locked file (the ide, git or webpack itself), so I gotta power down the whole thing for branch changes or test watchers.

I prefer having my editor run prettier on save, so I get the benefits of prettier formatting my ugly code immediately.

Also, lint-staged doesn't handle partially staged files properly: https://github.com/okonet/lint-staged/issues/62

I tried running it on save, but I can't "make" others configure their editors in a way I want (our fe team is around 10 ppl, be is much bigger).

Lint-staged can't handle partials, but precise-commits can, though we are using ls for now and will see how much this hurts in terms of partials.

> I can't "make" others configure their editors in a way I want

We run `prettier -l` in CI, so it's up to each person to decide how they want to make sure their code is prettier-ed before being pushed.

I'll check out precise-commits, thanks.

Why not use gulp-watch or equivalent build tool in your stack somewhere so everytime a file is saved it gets ran through prettier?
Totally agreed. The pre-commmit hooks do tend to have a lot of tests and enabling in feature branches will be a pain but these tools are needed in order to have stricter checks and ensuring that people of all experience levels continue working without destroying the code quality
> all the the cool kids do...

Am I alone in being annoyed by this phrase? Most of us here are grown adults, not 14 years old and this isn't high-school anymore.

Maybe. I'm close to fourty and to the sixty year old guy in the cafeteria I'm a kid (he literally callse me that, I just chuckle about it).

Sorry if it offended you, meant no harm - maybe little sarcasm about how fast frontend tech moves these days, but that's all.

no docker? amateur
No docker here and it hurts us, but it's just impossible to get the cms and core backend into docker containers. I heard all kinds of smartypants recommendations from yes you can to look for another job. Whatever.
I think no one's arguing that, if your project calls for it, you could just write javascript and commit it to a repository and be done about it.

All these tools just add guarantees to the quality of code in a codebase so that it's easier for a lot of people to work on the same app. Is it slower? Sure. Is it worth it to keep from deploying bugs? Also probably sure.

As a side note, I'd argue that running tests should probably not block you from committing code, but it should keep you from deploying code. I work at a company where our hooks are (usually) pretty fast, but keep you from having to rerun a much larger test suite.

Does it work with Typescript? If not, is there a TS equivalent?
Yes, TS support was baked in recent versions
It works perfectly with Typescript
What if we source control straight up AST instead of code? Each tool can decide how to render it...

I bet if Github supports such thing it will become standard

Well, you can already commit an AST if you really want to: just serialise the ESTree[0] to JSON and commit that.

But committing unreadable JSON files to version control rather defeats most of the features of version control.

[0] https://github.com/estree/estree

(comment deleted)
One thing that bugs me about Prettier is that JSX intentionally does not respect your quote setting -- it always uses double quotes. It's not a big deal but it's such weird issue to put your foot down over. Make it respect your setting and be done with it.
They shouldn't even be used interchangeably... if you have two different ways of doing something, you put that bit of information to good use, not make a mess of it. Personally I always use double quotes should for user-facing (generally, i18n'able) strings, reserving single quotes for internal strings/symbols. IMHO everyone should do this.
Single quotes are not valid in JSX.
That's not true.
Huh. You’re right. I’m fairly sure it used to be true.
Isn’t there a Paredit somewhere [1] for JavaScript? After all lisps are unreadable...

ducks

1: http://danmidwood.com/content/2014/11/21/animated-paredit.ht...

After three weeks of writing Javascript I don't understand how people bare with writing so damn much of it. I need to rest my hands from all the damn typing and reorganizing parentheses and braces, moving functions and typing return all the damn time.
On a related note: if you're looking for a unified linter toolkit, try out coala [1]. I'm a core maintainer, so if there is anything you want to know, feel free to ask me.

P.S. we now have an issue about about integrating Prettier into coala.

[1] https://coala.io/

What are everyone's strategies to adopt a tool like this? Do people run prettier over their entire codebase in one PR and call it a day?
Seriously, try out https://StyleCI.io it runs automatically Prettier on any branch you wish (can be disabled).

Plug: I make StyleCI.

Formatting per file/directory is a feasible solution. Another approach could be that you integrate it in your editor, and on every file that you work, on pressing save, it gets formatted. Thus you can convert it file by file. If you do it all at once, it would be a big diff and blame will always point to that commit and you would have some problems because of it
> Another approach could be that you integrate it in your editor, and on every file that you work, on pressing save, it gets formatted. Thus you can convert it file by file.

It means that your actual changes will be lost in a big diff of cosmetic changes. I think a better option is to convert the whole codebase in one commit and only after that run it on file save.

Do you have experience doing this? We are worried that one can't feesable click test an entire applications worth of prettier changes in a single PR.
Since prettier formats using the javascript AST, it should not introduce any bugs.
It's great until you have that one dev who automatically runs prettier on any opened file and then commits formatting changes all over the place. Code review then shows diffs which are 50% formatting in unrelated files.

Automation like that should really be team-consent-based in my opinion.

Prettier has made me change the code I write. It is now practical to write JS code as ternary expressions instead of if statements.

Here's an example:

  const x = !(result instanceof Skip)
    ? result
    : typeof obj === "object"
      ? traverseObject(Object.keys(obj))
      : Array.isArray(obj)
        ? traverseArray(obj)
        : new Skip("Not found.");
This was very hard to do prior to prettier; ternaries become very hard to read unless you carefully format them. If you're programming in this style, you'll find yourself reaching for IIFEs (immediately invoked fns) quite often, since JS doesn't yet have do expressions[1]. Here again, harder without prettier.

  const x = items.length
    ? (() => {
      const result = parse(deep(schema, params))
      return !(result instanceof Skip) ? result : traverseArray(items.slice(1));
    })()
    : new Skip("Not found.");
[1] https://babeljs.io/docs/plugins/transform-do-expressions/

+ Minor edits for clarity

Both of these things are way too hard to read and whilst they might be pretty you're massively screwing over whoever has to maintain your code lol
Agreed. Formatted code does not allow you to write stuff that is difficult to understand/reason about
The same code written with if conditions will have very similar text, will be slightly longer, have a possibility of 'return' statements anywhere in the text, and more importantly - might have embedded mutations.
... and will be much easier to instantly grok for almost everyone
I won't win this argument, and ymmv. :)

But personally, every identifier being a 'const' instead of a 'let' helps me reason about it much better, especially when the code is purely algorithmic. An alternative might be to use something like Facebook's Reason, where such code can be concise and idiomatic.

there is a tradeoff between ease of comprehension for everybody and syntactic simplicity (that is easy to comprehend for those familiar)
And full of missing return statements and corner cases. if it only were possible to put an expression anywhere you want :(
There's nothing wrong with if statements. If you can't even understand the code yourself it's a sign that it needs to be rewritten.

  function x(result, Skip, obj, traverseObject, treverseArray) {
    if(! result instanceof Skip) return result;
    if(typeof obj === "object") return traverseObject(Object.keys(obj));
    if(Array.isArray(obj)) return traverseArray(obj);
    
    return new Skip("Not found.");
  }
Agreed. I don't see what is so evil about early returns, they seem very clear to follow to me. Especially with proper IDE syntax highlighting.
That is terrible...

There is no performance gain, it's not particularly clever. Even if it's formatted better, I doubt this is easier to read than a few if statements for most people.

I was hesitant at first, but it took me less than a week to adopt it and be convinced it makes it much painless and easier to write JS. I missed it when writing Ruby code, until I discovered Rufo [1], a (still young) Prettier-like formatter for Ruby. They are now both part of my toolkit, bot the best!

[1] https://github.com/ruby-formatter/rufo

I was just saying to a colleague today; Prettier is the friend who only ever points out your flaws.
How fast does it prettify 10k LOC ?
If you have 10k LOC in a single file, you have bigger problems to worry about
Can you elaborate on what problems that would cause ? 10k LOC may be a bit extreme. Although having everything in the same place makes it easier to refactor and maintain. Breaking something up adds complexity, and is especially bad if it entangles itself with other parts of the code-base. I'll take one well structured file over 10k files with circular dependencies. If something can be lifted out into a library, of course you should do so, but breaking something for it's own sake is bad. For example include files within include files. Or include files disguised as modules.
Javascript modules were created for this purpose only. Have them as separate files while developing, have it readable and then you can always bundle them in a single file while deploying
On my systems it runs at 2.8k LOC per second. So 10k LOC would take 3.6s
Great tool, thanks for this.

I've been massively annoyed with the obsession of making the code look exactly the same in every of its parts. Ten years ago, I could tell which of my coworkers wrote a piece of code based on its style only. It was not especially needed, given we had git (and svn before that) to tell who authored a piece of code, but it was pleasant to recognize this or that developer's style. It was not radically different styles, we were still agreeing on tabs vs spaces and how many spaces, it was more subtle. We were authors.

But now that we psychorigidly don't want to see two pieces of individuality in the same codebase, be it as syntax or sometimes even as methods preferences to achieve a task, such tool as prettier or gofmt are incredibly useful. At least, we don't waste time on that.

Why would you be annoyed by the avoidance of merge conflicts?
Why would developer style cause merge conflicts? We did just fine, thanks.
When two people touch the same file and format it differently you get a merge conflict. Even if the actual code is identical.

The only way I can imagine how you never ran into this is that either your team is tiny, or that people don't touch other people's code. Both of which are not an option as you grow.

I might be extremely tolerant but I've never had any issues with formatting. I however see the value of this when working with a "formatting nazi" ... It's a form of bike shedding, where it's much easier to have an opinion on formatting, then it is to have an opinion on design and implementation. (so I hope they don't add any configuration options)
Is there a tool like this for Java? Something IDE-agnostic we can hook into a pre-commit hook.

Oh speaking of, we put prettier in a pre-commit hook, which grabs staged code, prettifies it and re-stages it. Works like a charm. We use https://github.com/okonet/lint-staged to perform this.

Prettier docs mention that support for Java is WIP
Don't forget to add a conf file (ex. prettierrc), editor plugins have different defaults.
As mentioned in the post, I have set my configuration in VS Code's settings itself.
I was skeptical about Prettier at first, I wasn't really fond of applying a formatting that wasn't mine. Then I tried it on small projects... to discover Prettier was freaking awesome. I can't not use it now, it just permanently fixes the formatting problem. I wish there was a tool like this for every other language I have to use
They are working on adding support for more languages
I'm not very familiar with JavaScript tools. Are there any good formatters that work similarly (parse the code and work from the AST) but are not so opinionated?

What I want out of code formatters (for any language, not just JavaScript) is flexible configuration so that I can set up two configurations.

1. A configuration that outputs the style that my employer or the project I'm contributing to has standardized on.

2. A configurations that outputs the style that I prefer.

I picked my styles in the languages I use because they make the code easier to read for me. If the company or project standard style is different I'll be more productive if I can convert my copy to my style while I work on it.

The opinionated formatting is what makes prettier great. A lot of configuration can be confusing for people to go through and pick a standard
Couldn't a configurable formatter ship with preset configurations for the major styles used for each language? For most people, who are probably using one of a handful of common styles, configuration would just consist of setting one option.