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)
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
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!
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 '{'.
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.
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.
> 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.
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.
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!
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.
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 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)
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.
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
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.
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.
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.
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.
I've applied it to this app at some point: 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.
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.");
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.
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 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!
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
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.
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.
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
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.
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.
128 comments
[ 0.94 ms ] story [ 150 ms ] threadWe’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)
Wish all languages had this sort of thing. It really has made reviewing and editing code much more pleasant at my company.
```
class Demo extends React.Component<{}, {}> {
}```
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.
And contrary to what you might expect, Prettier basically never makes stupid formatting choices. It’s incredibly nuanced.
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.
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.
https://imgur.com/a/6PkSi
What on earth would prettier include to make it that much more extensive?
Does VS format on the fly, or only on save ?
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?
If that was a common feature in formatting tools more than a decade ago, then I missed it too.
VS Studio and IntelliJ have some language formatting but the difference between them and prettier feels huge.
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.
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.
Also, lint-staged doesn't handle partially staged files properly: https://github.com/okonet/lint-staged/issues/62
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.
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.
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.
Sorry if it offended you, meant no harm - maybe little sarcasm about how fast frontend tech moves these days, but that's all.
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.
It integrates prettier, eslint:fix, and tslint:fix as part of the build process. Uses husky to run as a precommit hook as well.
Life saver when developing.
I bet if Github supports such thing it will become standard
But committing unreadable JSON files to version control rather defeats most of the features of version control.
[0] https://github.com/estree/estree
ducks
1: http://danmidwood.com/content/2014/11/21/animated-paredit.ht...
P.S. we now have an issue about about integrating Prettier into coala.
[1] https://coala.io/
Plug: I make StyleCI.
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.
Automation like that should really be team-consent-based in my opinion.
Here's an example:
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. [1] https://babeljs.io/docs/plugins/transform-do-expressions/+ Minor edits for clarity
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 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.
[1] https://github.com/ruby-formatter/rufo
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.
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.
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.
https://github.com/google/google-java-format
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.