9 ms·
Using Prettier to format your JavaScript code
- NegativeLatency 9y agoHaving 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)
- kaiby 9y agoIt's also a great answer to dissenting opinions about code style. No more arguing about when to line break inside an 'if' statement.
- xab9 9y agoExactly. Lint and code formatters are a must with big teams - now we can concentrate on the code and not on the style.
- thatswrong0 9y agoAnd 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.
- swyx 9y agoah 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 } ```
- seepel 9y agoWe just turn off tslint formatting rules. There isn’t really a need for them if you are using prettier.
- swyx 9y agooh. unfortunately my team lead insists on having them. thanks anyway.
- mceachen 9y agotslint, 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.
- saranshk 9y agoI 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!
- b-glad 9y agoNpm install tslint-config-prettier and add it to the extends array in tslint.json to switch tslint rules to be compatible with prettier
- swyx 9y agoappreciate the tip, have an upvote
- NegativeLatency 9y ago
- saranshk 9y agoI remember reading that gofmt was one of the inspirations for prettier
- sawyerjhood 9y agoPrettier 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 9y agoIt's great to have reviews that do not involve discussions regarding formatting
- kbeckmann 9y agoI 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.
- saranshk 9y agoNone that I know of
- samnardoni 9y agoclang-fmt?
- kbeckmann 9y agoThanks, didn’t know about this tool.
- namanyayg 9y agoNice 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 9y agoThanks! I also have the extension installed in code.
- portlander12345 9y agoBesides 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.
- eknkc 9y agoThis is what I do writing Go. gofmt comes around and cleans up my mess when I save.
- saranshk 9y agoI 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)
- jwdunne 9y agoEven better if your editor auto indents. I use aggressive indent mode for Emacs and it works ok. Sluggish on large files though.
- josteink 9y ago> 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.
- tlrobinson 9y agoPrettier 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/6cad91b1203a7d2c174824a4d7814a42 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.
- vikeri 9y agoI 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?)?
- yiransheng 9y agoPrettier 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 9y agoI think the authors include people from React team and fb open source team has been innovating at scale since some time now
- xab9 9y agoYeah, 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 9y agoI 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 9y agoI 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 9y ago> 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.
- polskibus 9y agoDoes it work with Typescript? If not, is there a TS equivalent?
- saranshk 9y agoYes, TS support was baked in recent versions
- iMarv 9y agoIt works perfectly with Typescript
- polskibus 9y agoIncluding tsx?
- khaliqgant 9y agoI’ve been working on this: https://github.com/khaliqgant/typescript-build https://github.com/khaliqgant/typescript-build 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.
- msoad 9y agoWhat 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 9y agoWell, 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
- deleted 9y ago[deleted]
- ng12 9y agoOne 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.
- mehrdadn 9y agoThey 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.
- underwater 9y agoSingle quotes are not valid in JSX.
- ng12 9y agoThat's not true.
- underwater 9y agoHuh. You’re right. I’m fairly sure it used to be true.
- eecc 9y agoIsn’t there a Paredit somewhere [1] for JavaScript? After all lisps are unreadable... ducks 1: http://danmidwood.com/content/2014/11/21/animated-paredit.html http://danmidwood.com/content/2014/11/21/animated-paredit.ht...
- serpix 9y agoAfter 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.
- adtac 9y agoOn 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 9y agoWhat 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?
- jbrooksuk 9y agoSeriously, try out https://StyleCI.io https://StyleCI.io it runs automatically Prettier on any branch you wish (can be disabled). Plug: I make StyleCI.
- saranshk 9y agoFormatting 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 9y ago> 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.
- doubletgl 9y agoIt'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.
- jeswin 9y agoPrettier 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 9y agoBoth 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
- saranshk 9y agoAgreed. Formatted code does not allow you to write stuff that is difficult to understand/reason about
- jeswin 9y agoThe 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 9y ago... and will be much easier to instantly grok for almost everyone
- renchap 9y agoI 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
- neciu 9y agoI 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-9e35bace2f99 https://medium.com/@netczuk/your-last-eslint-config-9e35bace...
- pan69 9y agoI was just saying to a colleague today; Prettier is the friend who only ever points out your flaws.
- z3t4 9y agoHow fast does it prettify 10k LOC ?
- saranshk 9y agoIf you have 10k LOC in a single file, you have bigger problems to worry about
- z3t4 9y agoCan 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 9y agoJavascript 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
- z3t4 9y agoOn my systems it runs at 2.8k LOC per second. So 10k LOC would take 3.6s
- oelmekki 9y agoGreat 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 9y agoWhy would you be annoyed by the avoidance of merge conflicts?
- oelmekki 9y agoWhy would developer style cause merge conflicts? We did just fine, thanks.
- tokenizerrr 9y agoWhen 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 9y agoI 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)
- Cthulhu_ 9y agoIs 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.
- maelito 9y agoDon't forget to add a conf file (ex. prettierrc), editor plugins have different defaults.
- saranshk 9y agoAs mentioned in the post, I have set my configuration in VS Code's settings itself.
- thiht 9y agoI 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 9y agoThey are working on adding support for more languages
- tzs 9y agoI'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 9y agoThe opinionated formatting is what makes prettier great. A lot of configuration can be confusing for people to go through and pick a standard
- tzs 9y agoCouldn'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.
- bichiliad 9y agoThe 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.
- spectrum1234 9y agoI 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.