Hacker News new | past | comments | ask | show | jobs | submit login
Prettier 1.0 (jlongster.com)
270 points by vjeux on Apr 13, 2017 | hide | past | web | favorite | 76 comments

Prettier is a code formatter for JavaScript, like the hugely popular "gofmt".

Highlights of the 1.0 announcement:

- production-ready (and used, eg; React, Oculus, Cloudflare, etc)

- --no-semi option

- --use-tabs option

- parens that help indicate precedence

- many formatting improvements

There are a ton of edge cases in this work that really matter (read through the announcement for a few). Speaking as a contributor, this is some of the hardest stuff I've ever done (beats building a JS superset, http://lightscript.org). I've been super impressed by the prettier team.

We had configurability in early versions of gofmt but realized it was a mistake and kinda missed the whole point of having a code formatter, so we removed them.

The problem with doing the same in JS is that the language has been around much longer, and wasn't designed for use with a formatter. ASI failures is a great example.

Prettier has so far resisted configuration wherever possible; it has 8 options, compared with eslint's 260+.

While I understand the reasons for this (especially with the culture, for lack of a better word, around Go), I feel like this is a step backward in general. The "standard" Haskell formatter, hindent, did something similar. I found the maintainer's behavior admirable -- the style that was agreed on was very different from his own, but it was what he saw after analyzing publicly available code -- but what's the problem with custom formats if they're consistent across a whole codebase?

In the case of Go, it's really advantageous to be able to jump into anyone's project and be able to read it without the additional impedance of adjusting to the new formatting model. I didn't think this would be that significant until I started participating in the Go community. This works together with Go's reduced feature set, so everyone's code ends up looking very similar.

What's the advantage of project specific, custom formats?

It allows everyone in your company's dev organization share a common `standard` of JS style, which you have agreed on, even if it differs slightly in the way it bikesheds things like single-vs-double quotes or the presence of semicolons. (I mention `standard` because we use it as the basis for our linting rules, and would LOVE to use prettier to reformat our code.)

it's something that doesn't matter that you don't ever have to worry about again. it's a huge win.

Can it handle escaped json string constants?

For example this: http://whitneyland.com/2017/04/first-in-the-world-to-display...

You can try prettier online at https://prettier.github.io/prettier/

Not sure exactly what you mean, but here's an example with JSON: https://prettier.github.io/prettier/#%7B%22content%22%3A%22x...

Prettier doesn't support JSON files per se (and doesn't currently plan to [0]), so you need to provide a leading `x = {...` or similar to ensure the { is parsed as an object instead of a block.

[0] https://github.com/prettier/prettier/issues/322

Looks like it has no understanding of json at all.

If you have a constant like this, except really long and ugly, there's quite a bit that can be done to make the code more readable.

Maybe I'll add an issue and see if anyone else cares about it.

var simpleJson = '{ "DevelopersNeedUXToo": [ { "Color": "Red", "Name": "Lee" } ] }'

Prettier goes such a long way to enforcing standards on a language and ecosystem which otherwise has none or few. What standards do exist are frequently arbitrary, or enforced by legacy code at random companies. For example, the Airbnb JS style guide [1] recommends single quotes in JS, but double quotes for JSX properties. Why the difference? Why not stick with double quotes everywhere, as they are required in JSX blocks? Answer: legacy code at Airbnb [2]

I'm hoping to see similar efforts on project file/folder structure at some point. How often do two node projects created by different engineering teams end up with the same folder/file structure? There's nearly no strong community convention, unlike many other languages/frameworks. Rails, for example, famously touts that any engineer can walk onto another Rails project and have a reasonable suspicion of where to find a particular piece of code.

1: https://github.com/airbnb/javascript 2: https://twitter.com/hshoff/status/784205839347232768

One of the Airbnb style guide authors here.

The point about quotes comes up often. The important part for us is consistency at Airbnb. We use eslint to enforce and maintain the consistency. Would it be more consistent to treat strings the same everywhere? For some projects sure. We diverge from the community a bit in the sense that we treat JSX as not JS and we aim to be consistent about that. If your project treats JSX and JS the same then yes, we've certainly seen folks do this. As always, please do what works best for your team or project [1]. Forks encouraged.

I will say an added benefit of including a style guide in a project for large teams that may get lost jumping straight into prettier, has been helping our engineers become stronger javascript programmers in the process of learning our style guide. That's largely anecdotal evidence from my time at Airbnb and of course your mileage my vary.

Personally, I support the Prettier mission 100%. Easier consistency is huge. Removing barriers to contributing to open source projects is huge. PR reviews focused on what the code is doing vs painful style nits is huge. It's been great to see this come from the community and I look forward to seeing where the community takes it. Congrats to all of the contributors on the 1.0!

[1] https://github.com/airbnb/javascript/issues/102

Pretty Diff contains an option to convert string quotes to either double quotes or single quotes. This was a trivial update and I would be amazed if its absent in other beautifiers.

Yes, prettier has a `--single-quote` option (default false).

The amazing thing, for me, is:

1. Announced 2 months ago

2. Already adopted by, it seems, every major JS project. (https://twitter.com/jlongster/status/852532847252566017)

3. 7000 stars, 100,000 npm downloads/mo

Now some people will say it is a better mousetrap, but even now I can't tell you what the difference is between it and all the other linters. I can tell you that, based on the popularity, I would just default to this one and assume all this famous projects and people have worked it out.

How did it get it so popular? What made people want to try it out? Just word of mouth?

Speaking for myself, I've been waiting for 1.0 before using it, but I've been very excited for this project since its announcement. I've personally experienced how much time can be wasted bikeshedding over stylistic issues. In most cases, just picking a consistent standard is far more important than whatever the choice happens to be. Prettier will make almost all that bikeshedding unnecessary.

Even with ESLint having autofix capabilities, Prettier seems far more comprehensive in that regard. It also isn't doing exactly the same things as linters. They check for programming errors as well, not just stylistic issues. With those linters, you also need to decide how to configure the rules (though picking a preset can make that easier).

I have always loved that Python has an "official" style guide (https://www.python.org/dev/peps/pep-0008/), and gofmt (https://golang.org/cmd/gofmt/) is one of the reasons I want to try out Go, so Prettier is a great development in my opinion. I am optimistic that the community will keep on adopting it, helping make our code more readable and allowing us to focus on actually building libraries, tools, applications, etc. rather than arguing over where we should and shouldn't have spaces in our code.

Edit: my TL;DR answer would be that it's a virtually zero configuration way to guarantee stylistic consistency.

It's really better than a linter because a linter warns you of style errors, but you still need to invest time to fit it.

Whereas this just formats everything for you, set it up on file save and you're done. No more discussions on style and whatnot, your codebase is suddenly uniform.

Go has that with `go fmt` and it's very liberating.

Most notable feature of prettier being able to format based on the wrap length. I don't know about others, but I definitely switched to it just for that feature.

Aside from being good software, it was created by a prominent person in the React/JS community and co-developed by a well-known Facebook engineer in the React team. It was lucky to be adopted by large companies quickly, but a) easier to adopt something Facebook approved™ and b) it's painless to adopt since it does everything automatically.

All that, being a great tool, and some Twitter/Medium promotion = success.

Really looking forward to TypeScript support [0] as that's blocking me from using this in most of my work-related projects. Congrats to the team on 1.0!

0: https://github.com/prettier/prettier/issues/13

Yeah, that's what I thought when I saw this project for the first time today. And here I just started moving everything to typescript.

I recall the React team were discussing at what part of the build step they should include Prettier.

I believe there was an idea of adding it as a pre-commit hook, a second one as a manual step and another one as a post-commit amend.

Have we reached a consensus on that? Not up to date what they went with, what seems to be the best way to do this?

We currently do the same thing Jest does: no hooks, but we offer it as `npm run prettier`, and we also run the comparison on CI (so if the prettier output is different, the PR fails). This means the code is always checked in formatted, but people need to remember to run `npm run prettier` or CI will fail.

Interesting, thanks Dan.

I run it at pre-commit and in CI before approving a PR. Basically my thought is to trust my team to do it whatever way they want to, in the editor, manually, or as a commit hook; and then verify it on the backend before committing.

This is exactly right. First project I saw using this approach a couple years ago was Play Framework + scalariform.

I'm also curious about this. FWIW, I came across this post on adding Prettier as a pre-commit hook that might help others: https://medium.com/@brindelle/format-your-javascript-with-pr...

This is getting closer to my dream setup of being able to open files in my formatting, and saving them in the team's formatting.

Formatting source code feels like a complete waste of developer time and energy, especially when they don't agree with how the team has decided to format the code. I almost wish source code files could be just serialized ASTs and that a VCS could understand them making merges etc. even easier.

I'm surprised that doesn't exist. When I did a lot of Perl in a team environment, we used perltidy. Helpful since Perl does little to encourage uniformity.

It could take any sort of style in, and produce any sort of style out. Things like K&R blocks vs Allman-style blocks, tabs vs spaces, line wrapping, cuddled/not-cuddled else, etc.


Edit: this looks pretty close to the same thing for JavaScript. Missing some style options, and not command line driven, but the general idea seems close: https://github.com/benjamn/recast/blob/master/README.md

People here seem to approve it, but I feel unsure. Example with the matrix shows pretty well, why exceptions are always possible, no matter how detailed your styleguide is. And using comments to hold your auto-formatter back always baffles me. It seems so misaligned with the original purpose of writing the code (which comments are a part of).

It might be useful to re-format a completely messed up piece of code coming from the external world, but on the team I always prefer styleguides in the mood of "recommended, never enforced", which "prettier" is exact opposite of. That is, try to write like everyone else on the team does, but avoid re-formatting the code written by someone else, if there's no real need to do so. Obvious, strictly formal things like spaces instead of tabs, spaces outside of brackets (not inside of them), etc — this is one thing. But aligning pieces code to match some meta-pattern, or using longer/shorter lines than usual for some specific, "artistic" purpose — come on, this is not such a big deal. Consistency is overrated.

I feel like you have to give Go credit for exposing this type of productivity hack. Once you gofmt/goimports on save you will never go back.

Edit: If I had to program in JS I would definitely use this coming from Go.

gofmt helped drive the demand and popularity for prettier, but people have been trying to build something like it for JS since before Go existed [0].

Prettier has succeeded largely due to a better algorithm, which actually came from the haskell community, via Wadler's paper A Prettier Printer [1] (with an implementation available at [2]).

[0] js-beautify had its first commit in 2007: https://github.com/beautify-web/js-beautify/commit/e1ddc28b2...

[1] https://homepages.inf.ed.ac.uk/wadler/papers/prettier/pretti... [PDF]

[2] https://hackage.haskell.org/package/wl-pprint

I'll never understand code formatters. For me the idea of my code passing through a formatter, is like if accidentally I lost part of it: there is a lot of care in the way you write your code, even in the part that the compiler does not care about: spaces. Spaces are the rhythm of the code... not sure why one would write code without rhythm and later add a synthetic one.

You might be surprised at the quality of the output (obviously I'm biased). We've tried to choose what most people consider to be the best way to style code, and many times prettier ends up formatting complex code better than I would have manually. Also, the biggest benefit that a lot of people don't realize is it allows you to quickly restructure your code easily: http://jlongster.com/s/refactor.gif

I understand if the way prettier formats your code is not the way you would like, and is more of a hindrance than helpful. But I hope the above gif shows why it is freeing for a lot of people.

Also, note that prettier does keep the original blank lines in your code. That's where most of the rhythm comes from, and we allows authors to group code however they want. The rest of it is basically choosing whether to insert a space here or there or not.

I respect your work, antirez, and I hope you at least try it once! It's totally fine if it's not useful for you though.

Hello! Don't get me wrong, I'm not saying that code formatters are not useful, they are massively useful in order to turn badly formatted code into more readable code, and also when there is to integrate some code from a code base to another and needs to be re-formatted and so forth. What I find odd is that there are people using it as a "to go" solution for code indentation. The fact btw that it keeps the original blank lines is a great feature that saves a lot of semantics. Thanks for your comment!

There's two reasons, to me, why formatters make a lot of sense. First, working in large teams, not everyone will agree on a formatting convention and it's very difficult for people to internalize the convention and stick to it. This leads to, at best, inconsistencies in the code and, at worst, bike shedding discussions on which conventions to use that distract from shipping actual features. When HBO's Silicon Valley had its lead character lose out on a promising relationship because of a spaces vs tabs argument, it hit dangerously close for those of us that have had to endure a months-long meetingfest to arrive at a company standard for code formatting. Once you've been through that hell, you can appreciate the simplicity of just invoking a tool during the build process.

Second, there's what I'd call the "Mark Zuckerberg clothing" reason. When asked why he always wears the same style clothes, he said, "I really want to clear my life to make it so that I have to make as few decisions as possible about anything except how to best serve this community." Similarly, code formatting doesn't deliver value to customers/users. The more you can ignore it, the more you can focus on other things. When I first started using code formatters, they irked me greatly. But once you get used to them as a part of your process and start to feel comfortable reading the code they spit out, they transition to being liberating. The formatting fades into the background and all you see is the logic in the code. And I didn't realize just how much time I was spending getting indentation levels correct and aligning things until I entirely stopped doing those things. Now I write code that looks really ugly until I hit save and then it looks exactly the way that the rest of my code looks.

I've found this too.

Also: my code formatting has always been a bit unusual, in that I never put spaces in. Compared to what most people do, this is easier to type, because it doesn't require pressing the space bar as much. So code formatters are good for me, because I can keep not pressing space, and now nobody need ever know.

But, guess what: this means code formatters are good for you too. Because now you don't have to press space either.

Because your rhythm might be unique or confusing to your team members.

Using a tool like this you all share the same rhythm. No ones feelings get hurt, onboarding is simpler, code is easier to read.

That is one of the reasons I'm stuck with Python, I find it pleasant to read (I'm almost as productive as I used to be with Perl but at least I can understand my own scripts 6 months later).

I know, many people can't stand significant white space... The idea sounded weird for me too but after trying it for awhile I was hooked.

I think this is because you view yourself as more of a code author, and people excited for this announcement more frequently find themselves in the role of a code reader.

I was waiting the --no-semi option to start using Prettier. Thanks to the team!

The option seems to put semicolons at the front of your code instead of at the end. Am I wrong? Why is this attractive?

They specifically demonstrated a case where that's necessary [1], it doesn't always do that.

[1] https://github.com/feross/standard/blob/master/RULES.md#semi...

The example you found on the blog post was there to show how prettier handles conflicting cases. It will print them only in those cases.

I can't overstate how freeing coding with prettier has been -- often I'd find myself quickly grokking something and once I finally got it to "work," make sure it was all styled properly. Since using prettier, these things are one-and-the-same, which is a tremendous gain.

Something that's kind of tricky for me and my team is that we disagree on things like indentation and spacing in/around brackets and parens. The disagreement isn't just a "I think it should be done this way..." but "I actually understand code better when it's written this way..."

If we were to implement prettier, and chose to use 2-space indents, for a simple example, how would a 4-space developer fare when they pulled down the Prettified code? Would they just set up their own config locally based on their own standards?

That doesn't sound like a good idea (after all, there can only be one codebase in source control) but I believe it actually would be possible – and in fact, prettier would be a vital component to making it happen.

If you have a pair of particularly persnickety peers, you could theoretically:

1) run prettier with the company-wide config as a precommit hook (https://github.com/prettier/prettier#pre-commit-hook-for-cha...)

2) instruct your colleagues to have their editor run prettier with their own preferences on save.

This way, your colleagues can simply open a file locally and save it to see things their way – and the code will be back to company-normal when they commit. They'll still have to see that unbearable bracket-spacing during code review, of course.

Prettier doesn't have many configuration options (intentionally!) so they'd probably opt to use prettier-eslint or similar, which allows more configuration (at the cost of speed).

Hopefully, after trying this, they would come to the conclusion that life is better just using the defaults, two-space-indents be damned. Bikesheds are great places for compromise.

Like rattray mentioned, this is something that I think would be totally doable in Prettier (whether or not it would be wise is a separate issue).

I sort of deal with something like that even just personally. On my work machine I have nice screen real estate, but when I'm on the go on my 11" air I have prettier set up with a more generous character limit so I can see more on screen. If you combined this set up with something like the pre-commit hooks that OITT have suggested, I could then be looking at my own code slightly differently in two machines but the end result would be the same!

Your comment made me wonder, could tools like prettier be the first step towards developer-customized code styles?

See it as views. Code could be stored in a minified (spaces and new lines are not necessarily saved), and then every developer in the team can view the code in any style he chooses. His code would then be committed using the underlying "minified" format, so that the next developer can pick up that code and view it in his own code style.

Does that even make sense? What could be the gotchas of such a thing?

I suppose Prettier should make it possible for a developer to reformat the code the way they prefer when they pull it, work on it, then format it back to what the rest of the team has agreed on before they push. Unless it was completely automated it sounds like a pretty terrible way to work, though.

How are you doing it today?

You just have to settle on a style as a team and stick to it as a team. I'd say it doesn't make a ton of sense to have individual coding standards among a team.

How does Prettier compare to https://github.com/millermedeiros/esformatter, https://github.com/beautify-web/js-beautify, https://github.com/jedmao/codepainter, https://github.com/rdio/jsfmt, etc.?

Personally, I use TSLint with the tslint.autoFixOnSave VSCode setting, and couldn't be happier.

I think you could be happier but just don't know it yet. :)

Every lint ruleset I've ever used still leaves a TON of formatting discretion to the author – notably about where to wrap. Prettier will format code differently depending on how much space there is left to work with on the line – like a human would do, but always consistent.

It would be useful to compare with "eslint --fix" given Eslint can already reformat (on top of linting non-style things, and projects usually already have Eslint settings).

From the readme:

Unlike ESLint ... everything is fixable. This works because Prettier never "checks" anything; it ... parses your JavaScript into an AST (Abstract Syntax Tree) and pretty-prints the AST, completely ignoring any of the original formatting.

There's an extremely important piece missing from existing styling tools: the maximum line length ... (ESLint never knows how to fix it).


There's also prettier-eslint[1], which will run prettier and then eslint --fix on your code to try give you the best of both worlds.

[1] https://github.com/prettier/prettier-eslint

I use prettier-eslint which (as dahjelle posted) runs prettier (for spacing) then eslint (for syntax fixes). I absolutely love it.

What's the best way to add this to an existing project?

Going through all code at once would destroy all relevant vcs history and git blame. Maybe before each substantial edit on a file first run it through prettier and then make your real changes in a separate commit?

You can have git diff/blame/etc ignore stylistic changes by configuring prettier as a textconv [1]. I'm building a `git diff` wrapper that does this for you [2].

[1]: https://git.wiki.kernel.org/index.php/Textconv

[2]: https://github.com/josephfrazier/prettier-diff

One of those tools that you don't realize how much you need it until you use it.

I love this thing, have it on auto save. It saves so much time. Now I can write remove a nesting, leave dangling commas and I don't have to even waste a second to clean it up. Just hit save and everything slips into place.

Prettier is like rainbow sprinkels on top of my code.

I write vastly different JS as Prettier formats (single quotes, no semicolons, etc.), but after I hit save everything just looks 'normalised'

I really like it for personal stuff.

I'd like to hear how people are using it on teams. With some effort I got it working on save in emacs, but asking other people to please install more tooling is not always easy.

I do have some authority over package.json though. How would you make it just work for everyone (using atom, vim, etc...)

One option is to add prettier as a precommit hook, eg; https://github.com/prettier/prettier#pre-commit-hook-for-cha... which doesn't require editor integrations at all.

There are integrations for most editors (Atoms, Emacs, Vim, Neovim, VSCode, VS, Sublime Text, JetBrains):


Does it jump your cursor around? I'd be interested in your config if it doesn't.

How can I use this on file save within Atom?

Edit: Oh here we go: https://github.com/prettier/prettier-atom

How is prettier compared to vscode autoformat feature?

What is the Prettier equivalent for SCSS and HTML?

I don't know that there is one. From the repository README:

> Prettier bans all custom styling by parsing it away and re-printing the parsed AST with its own rules that take the maximum line width into account, wrapping code when necessary.

HTML Tidy does the same job for HTML.

Is this basically clang-format for JS?

Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | Legal | Apply to YC | Contact