
Using Prettier to format your JavaScript code - saranshk
https://www.wisdomgeek.com/web-development/using-prettier-format-javascript-code/
======
portlander12345
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.

~~~
cc81
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.

~~~
scrollaway
I miss Prettier in Python. YAPF is atrocious. Good news is some Prettier
contributors (let's call em pretties) are working on Python support.

~~~
PetitPrince
What are your gripes with yapf ? I'd like to use a formatter for my Python
code; should I rather wait for something better ?

~~~
scrollaway
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.

------
xab9
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.

~~~
tlrobinson
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](https://github.com/okonet/lint-staged/issues/62)

~~~
xab9
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.

~~~
tlrobinson
> 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.

------
tlrobinson
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](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...](https://gist.github.com/tlrobinson/6cad91b1203a7d2c174824a4d7814a42)

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.

~~~
vikeri
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?)?

------
jeswin
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/](https://babeljs.io/docs/plugins/transform-do-expressions/)

\+ Minor edits for clarity

~~~
morrbo
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

~~~
jeswin
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.

~~~
GordonS
... and will be _much_ easier to instantly grok for almost everyone

~~~
jeswin
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.

------
sawyerjhood
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 '{'.

~~~
saranshk
It's great to have reviews that do not involve discussions regarding
formatting

~~~
kbeckmann
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.

~~~
samnardoni
clang-fmt?

~~~
kbeckmann
Thanks, didn’t know about this tool.

------
msoad
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

~~~
thomasfoster96
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](https://github.com/estree/estree)

------
oelmekki
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.

~~~
tokenizerrr
Why would you be annoyed by the avoidance of merge conflicts?

~~~
oelmekki
Why would developer style cause merge conflicts? We did just fine, thanks.

~~~
tokenizerrr
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.

------
z3t4
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)

------
ng12
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.

~~~
underwater
Single quotes are not valid in JSX.

~~~
ng12
That's not true.

~~~
underwater
Huh. You’re right. I’m fairly sure it used to be true.

------
tzs
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.

~~~
saranshk
The opinionated formatting is what makes prettier great. A lot of
configuration can be confusing for people to go through and pick a standard

~~~
tzs
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.

------
NegativeLatency
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)

~~~
swyx
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

}

```

~~~
b-glad
Npm install tslint-config-prettier and add it to the extends array in
tslint.json to switch tslint rules to be compatible with prettier

~~~
swyx
appreciate the tip, have an upvote

------
yiransheng
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](https://github.com/prettier/prettier/issues/2097))

~~~
saranshk
I think the authors include people from React team and fb open source team has
been innovating at scale since some time now

------
namanyayg
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.

~~~
saranshk
Thanks! I also have the extension installed in code.

------
renchap
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](https://github.com/ruby-
formatter/rufo)

------
spectrum1234
I love this for when I have a huge unknown object that I need to run a diff
on.

Just console.log(JSON.stringify(object)) and paste into your editor. Then just
remove the string around it and on save, _POOF_ you have a nicely structured
object. Do this with your diff state in another commit and you just diff-ed an
insanely large mess of code.

This won't work on online diff tools because the format will be different
without prettier.

------
bichiliad
The team I work on just rolled out Prettier to a pretty large codebase (~10k
files) pretty painlessly.

The one annoying part was the initial roll-out, and a subsequent update, that
caused code diffs to be pretty wild. I'd recommend formatting everything at
once when you first deploy Prettier. You lose the ability to easily git blame
files, but you make everyone's diffs way less horrible.

------
Cthulhu_
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](https://github.com/okonet/lint-staged)
to perform this.

~~~
sa46
Google Java format works if you're okay with the Google style guide.

[https://github.com/google/google-java-
format](https://github.com/google/google-java-format)

------
thiht
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

~~~
saranshk
They are working on adding support for more languages

------
neciu
I like to keep "similar" things together, that's why I prettify my code on
linting step. You can read more about it here:
[https://medium.com/@netczuk/your-last-eslint-
config-9e35bace...](https://medium.com/@netczuk/your-last-eslint-
config-9e35bace2f99)

------
adtac
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/](https://coala.io/)

------
adenta
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?

~~~
saranshk
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

~~~
laurent123456
> 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.

~~~
adenta
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.

~~~
laurent123456
I've applied it to this app at some point:
[https://github.com/laurent22/joplin](https://github.com/laurent22/joplin) And
didn't notice any bug or any issue in any of the three apps and all the tests
were still passing.

------
pan69
I was just saying to a colleague today; Prettier is the friend who only ever
points out your flaws.

------
maelito
Don't forget to add a conf file (ex. prettierrc), editor plugins have
different defaults.

~~~
saranshk
As mentioned in the post, I have set my configuration in VS Code's settings
itself.

------
eecc
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...](http://danmidwood.com/content/2014/11/21/animated-paredit.html)

~~~
serpix
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.

------
polskibus
Does it work with Typescript? If not, is there a TS equivalent?

~~~
iMarv
It works perfectly with Typescript

~~~
polskibus
Including tsx?

------
z3t4
How fast does it prettify 10k LOC ?

~~~
saranshk
If you have 10k LOC in a single file, you have bigger problems to worry about

~~~
z3t4
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.

~~~
saranshk
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

