Prettier is an opinionated code formatter.

  • By Prettier
  • Last update: Jan 8, 2023
  • Comments: 17

Prettier Banner

Opinionated Code Formatter

JavaScript · TypeScript · Flow · JSX · JSON
CSS · SCSS · Less
HTML · Vue · Angular
GraphQL · Markdown · YAML
Your favorite language?

Github Actions Build Status Github Actions Build Status Github Actions Build Status Codecov Coverage Status Blazing Fast
npm version weekly downloads from npm code style: prettier Chat on Gitter Follow Prettier on Twitter

Intro

Prettier is an opinionated code formatter. It enforces a consistent style by parsing your code and re-printing it with its own rules that take the maximum line length into account, wrapping code when necessary.

Input

foo(reallyLongArg(), omgSoManyParameters(), IShouldRefactorThis(), isThereSeriouslyAnotherOne());

Output

foo(
  reallyLongArg(),
  omgSoManyParameters(),
  IShouldRefactorThis(),
  isThereSeriouslyAnotherOne()
);

Prettier can be run in your editor on-save, in a pre-commit hook, or in CI environments to ensure your codebase has a consistent style without devs ever having to post a nit-picky comment on a code review ever again!


Documentation

Install · Options · CLI · API

Playground


Badge

Show the world you're using Prettiercode style: prettier

[![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=flat-square)](https://github.com/prettier/prettier)

Contributing

See CONTRIBUTING.md.

Github

https://github.com/prettier/prettier

Comments(17)

  • 1

    [resolved] [HTML] allow corresponding option to jsxBracketSameLine

    Note: Read this comment to make sure you’re up-to-speed on what this issue is and is not about: https://github.com/prettier/prettier/issues/5377#issuecomment-628213559


    For React/JSX - Prettier has an option to allow tags to close on the same line as the declaration, rather then on a new line: jsxBracketSameLine: true:

    <button
      className="prettier-class"
      id="prettier-id"
      onClick={this.handleClick}>
      Click Here
    </button>
    

    jsxBracketSameLine: false:

    <button
      className="prettier-class"
      id="prettier-id"
      onClick={this.handleClick}
    >
      Click Here
    </button>
    

    With Prettier 1.15.1, at least for the Angular parser, there is no corresponding option, so all HTML is formatted like this: Input:

    <my-component class="wcd-flex-1 dialog-contents wcd-scroll-vertical"
    		      [foo]="bar">
    </my-component>
    

    Output:

    <my-component
        class="wcd-flex-1 dialog-contents wcd-scroll-vertical"
    	[foo]="bar"
    >
    </my-component>
    

    Playground link

    It would be nice to have a flag to set it such that the output of the above would be:

    <my-component
        class="wcd-flex-1 dialog-contents wcd-scroll-vertical"
    	[foo]="bar">
    </my-component>
    
  • 2

    Indent script and style tags content in *.vue files

    Prettier 1.10.2 Playground link

    When I have a Vue.js file:

    <script>
        export default {
            mounted() {
                console.log('Component mounted!')
            }
        }
    </script>
    

    How do I stop prettier changing the indentation to:

    <script>
    export default {
        mounted() {
            console.log("Component mounted!");
        }
    };
    </script>
    
  • 3

    Space after function name in declarations

    NOTE: This issue is raised due to confusion in #1139. NOTE: Feel free to use the 👍 and 👎 buttons to indicate your preferences, but please refrain from commenting unless you’ve read every comment and made sure yours says something that has not been said before.

    This issue is only about outputting these spaces:

    function identity (value) {
      //             ^ space here
      return value;
    }
    
    function identity <T>(value: T): T {
      //             ^ space here
      return value;
    }
    
    class A {
      method () {
        //  ^ space here
      }
    }
    
    const obj = {
      method () {
        //  ^ space here
      }
    }
    

    (Prettier currently does not put spaces in those positions.)

    🗒 NOTE: This issue is not about anonymous functions:

    const identity = function (value) {
      //                     ^ space here: SEE #3847!
      return value;
    }
    

    Anonymous functions are tracked in #3847!

    The key arguments is: Searchability: You can find any function or method declaration my searching for e.g. method ( or identity <, or even just name[space] (mostly).

    It also provides a clear and immediate difference between declaration and invocation.

    (There are many existing comments in favour of this style, notably: https://github.com/prettier/prettier/issues/1139#issuecomment-316096507 and the majority of the discussion from https://github.com/prettier/prettier/issues/1139#issuecomment-361515396 onwards.)

  • 4

    Prettier 2.0 (old)

    Note added by @j-f1:

    This is NOT the current plan for Prettier v2.0. We’ve significantly scaled back our plans for what Prettier 2.0 will do, allowing us to get a less-controversial release out sooner: https://github.com/prettier/prettier/issues/6888


    I've been thinking a bit about what we would do if (don't create a milestone just yet :wink:) we were to do a Prettier 2.0 release with some API/CLI breaking changes. No significant changes to code formatting other than perhaps changing some defaults.

    Easy?

    • #68/#3469 - Change default value for trailingComma to "es5". The diff advantages alone are excellent, and this seems to be commonplace among the most popular JS projects.

    CLI:

    • #2691 - CLI defaults to "**/*.{js,ts,...}". People should just be able to do prettier --write without passing messy globs #0CJS

    • #2846 - Replace the "parser" option with "language". e.g. echo ".foo {}" | prettier --language css Keep --parser flow or perhaps support something like --parser.js flow for future extensibility.

    • Remove --flow-parser option. Has been deprecated for a long time.

    For debate

    • #838 - Consistently add quotes to object keys. e.g. put quotes around origin in this example:

      const headers = {
        'origin': 'foo.com',
        'access-control-allow-origin': '*',
      };
      
    • Change the default value for singleQuote to true

      • Airbnb, standard, xo, and probably the majority of JS devs prefer this. Maybe do a Twitter poll to gauge opinions on this.

    To be clear, the Airbnb config requires single quotes for JS and double quotes for JSX.

    Outdated

    • #2884 - Remove the default parser. Fixed by #4528

    • ~#1139 - Put a space after the n in function () {}~

  • 5

    Markdown[next branch]: Do not insert spaces between Chinese/Japanese & latin letters

    Description

    This PR is for fixing #6385 in the coming version 3.0, and introduces the change in my hotfix plugin to the original Prettier. Remove the option from and optimize #8526

    Note: this is for the next branch, not the main branch.

    If I do not have to add anything in changelog_unreleased/markdown/, I will change this to the normal (not draft) PR.

    Fixes #6385

    Checklist

    • [x] I’ve added tests to confirm my change works.
    • [x] (If changing the API or CLI) I’ve documented the changes I’ve made (in the docs/ directory).
    • [x] (If the change is user-facing) I’ve added my changes to changelog_unreleased/*/XXXX.md file following changelog_unreleased/TEMPLATE.md.
    • [x] I’ve read the contributing guidelines.

    Try the playground for this PR

    I just did yarn jest --updateSnapshot.


    P.S. (2022-12-11) This patch is enabled in Prettier 3.0.0-alpha.3 or later.

  • 6

    Feature Request: breakBeforeElse

    I know the goal of prettier is to standardize on a style, but it is also difficult since this did not come out at the same time as the language.

    Our team uses the exact same style as prettier except placement for else statements. It is effectively blocking us from adopting this awesome library.

    We prefer break before else to allow for cleaner comments.

    // This does something
    if (a) {
    }
    // This does something else if
    else if {
    
    }
    // This does something else
    else {
    
    }
    

    Which is nicer than.

    // This does something
    if (a) {
    
    // This does something else if
    } else if {
    
    // This does something else
    } else {
    
    }
    

    However this is preference and would be awesome if this was added as an option to prettier.

    @vjeux showed how easy it is to do https://github.com/prettier/prettier/pull/837 and apparently @jlongster likes it :) https://twitter.com/jlongster/status/834407714965057540

  • 7

    feat: support HTML/Vue/Angular

    Fixes #1882 Fixes #2097 Fixes #3767 Fixes #4095 Fixes #5098 Fixes #5263


    Try out this PR:

    yarn add ikatyang/prettier#feat/html/todos
    
    # *.html defaults to `--parser html`
    yarn prettier filename.html
    
    # *.component.html defaults to `--parser angular`
    yarn prettier filename.component.html
    
    # *.vue defaults to `--parser vue`
    yarn prettier filename.vue
    
    # NOTE: framework-specific formatting won't be triggered in `--parser html`
    

    or preview playground (hard reload to ensure it's the latest one).

    Please note that syntax errors produced by child language in the playground is a known issue, it won't happen if you use it locally (i.e., prettier something.html).


    Already supported on master:

    • HTML: support front matter
    • HTML: whitespace-sensitive formatting
      • support magic comment (<!-- display: block -->)
      • --html-whitespace-sensitivity <css|strict|ignore>
        • magic comments take precedence
        • (default) css: respect default css style (safe in the most cases)
        • strict: every element is considered whitespace sensitive (the safest)
        • ignore: every element is considered whitespace insensitive (dangerous)
    • HTML: support IE conditional comment (<!--[if IE]><![endif]-->)

    Added in this PR:

    • HTML: support pragma (<!-- @prettier -->)
    • JS: support lit-html (html`<div>Hello ${name}!</div>`)
    • HTML: support CDATA (<![CDATA[ content ]]>)
    • HTML: support interpolation ({{jsExpression}})
    • HTML: format vue binding syntax as js expression (:class, v-if, v-bind:id, @click)
    • HTML: format angular binding syntax as js expression (*ngIf, [target], (target), [(target)])
    • JS: support angular inline template (@Component({ template: `<div>Hello World</div>` }))
    • HTML: disable custom self-closing tag recognition
    • Vue: replace with HTML parser + enable custom self-closing tag recognition

    TODOs:

    • [x] HTML: format <script type="module"> (#3767)
    • [x] HTML: format <script type="text/markdown"> (#4095)
    • [x] HTML: no unexpected output for style content (https://github.com/prettier/prettier/pull/5259#issuecomment-429571079)
    • [x] HTML: allow tagging HTML templates with comment (https://github.com/prettier/prettier/pull/5259#issuecomment-429571079)
    • [x] HTML: move framework-specific formatting to --parser <vue|angular>
      • *.vue defaults to vue parser
      • *.component.html defaults to angular parser
      • the rest *.html defaults to html parser
    • [x] Vue: support v-for (https://github.com/prettier/prettier/pull/5259#issuecomment-429685174)
    • [x] Vue: support js statements for v-on:click, @click (https://github.com/prettier/prettier/pull/5259#issuecomment-430007170)
    • [x] Vue: support slot-scope (https://github.com/prettier/prettier/pull/5259#issuecomment-430007958)
    • Angular: support Angular-specific syntax (https://github.com/prettier/prettier/pull/5259#issuecomment-429639193)
      • [x] Angular action for (target)="input"
      • [x] Angular binding for [target]="input"
      • [x] Angular interpolation for {{input}}
      • [x] Angular template bindings for *directive="input"
    • [x] HTML: fix "Comments are discarded from binding attributes" (#5263)
    • (let me know if I missed something)
      • (please report issues separately so that we can easily hide resolved comments)

    • [x] I’ve added tests to confirm my change works.
    • (If changing the API or CLI) I’ve documented the changes I’ve made (in the docs/ directory)
    • [x] I’ve read the contributing guidelines.
  • 8

    Option to retain multi-line props in JSX/HTML

    Right now I'm finding that Prettier collapses JSX attributes onto a single line, up until the column width. This (in my opinion) feels much harder to read as it requires the eyes to constantly scan left to right rather than "glance" at a single block.

    Would you be open to an option that disables this forced single-line output?

    Prettier 1.7.4 Playground link

    Input:

    const f = () => (
      <Foo
        hello={baz}
        how={are}
        you={a}
        hi={c}
      />
    )
    

    Output:

    const f = () => <Foo hello={baz} how={are} you={a} hi={c} />;
    

    Expected behavior: Retain line breaks.

    Update:

    I opened this a long while back but after two years of using Prettier I absolutely, without question, and without hestitation, support the settings currently in Prettier and further -- believe that all of these personal preferences simply vanish from sight after using Prettier for more than a few days, as if one never even had them. They vanish into the delight of not having to worry about preferences anymore, and all of the energy / time savings that come from that. I am a 👎 on adding additional configuration in this regard.

  • 9

    Space after function keyword in anonymous functions

    NOTE: This issue is raised due to confusion in #1139.

    This issue is only about anonymous functions:

    const identity = function (value) {
      //                     ^ space here
      return value;
    }
    

    (Prettier currently does not put a space there.)

    🗒 NOTE: This issue is not about having a space after the function name:

    function identity (value) {
      //             ^ space here: SEE #3845!
      return value;
    }
    

    Space after function name is tracked in #3845!

    The key argument is: Consistency: This means that there's always a space after the function keyword.

  • 10

    Angular Output/Input decorators are moved to new line

    Prettier 1.14.0 Playground link

    --parser typescript
    

    Input:

    @Component({
      selector: 'toh-hero-button',
      template: `<button>{{label}}</button>`
    })
    export class HeroButtonComponent {
      @Output() change = new EventEmitter<any>();
      @Input() label: string;
    }
    

    Output:

    @Component({
      selector: "toh-hero-button",
      template: `<button>{{label}}</button>`
    })
    export class HeroButtonComponent {
      @Output()
      change = new EventEmitter<any>();
      @Input()
      label: string;
    }
    
    

    Expected behavior: Decorators are kept on the same line.

    More details: When using Angular, it's recommended to follow their style guide, which specifies:

    Placing the decorator on the same line usually makes for shorter code and still easily identifies the property as an input or output. Put it on the line above when doing so is clearly more readable.

    Angular classes are a valid (and common) use-case for Prettier, but with Prettier 1.14 (relevant PR) it deviates from the Angular style guide, causing unwanted changed for most people using Angular. Note that the above code example (input) is taken directly from the Angular style guide.

    The original PR to change this behavior mentions that mobx is the only library using same-line decorators, which is clearly not the case, with Angular being a (big) second one.

    To avoid reverting the new behavior completely, which is probably still wanted by some people - I suggest adding an option to the config to keep the old behavior, or prefer the new one (default should be discussed further).

  • 11

    Change HTML/JSX formatting to have one attribute/prop per line

    Similar to what was done for #3847 I think it best to break some of the discussion from #3101 into a new issue that people can 👍 or 👎.

    I'm proposing that for HTML and JSX to have Prettier always have one attribute/prop per line (and thus not respect the developer's original preference). Code would then be formatted as shown below. This is in contrast to the current behaviour where we fit as much as possible with the print-width.

    Expected behavior:

    <MyComponent lorem="1"/>
    
    <MyComponent
      lorem="1"
      ipsum="2"
    />
    
    <MyComponent
      lorem="1"
      ipsum="2"
      dolor="3"
    />
    

    This suggestion for one attribute/prop per line was proposed several times in the discussion of #3101 but I think it is clearer if this is pulled into it's own proposal. The original proposal in #3101 is that Prettier would add an option to preserve original formatting which, while I agree with the author with the style that they want, I don't think a) an option, nor b) preserving original formatting follows the aims for Prettier (see also #2068). Instead I think the aims of #3101 are better served by this proposal to ignore the print-width and always place attributes/props on new lines (assuming that there is more than one).

    This style appears to be the most common formatting for Angular, Vue and React from what I can tell. It style appears to be the style enforced by the rules:

  • 12

    Reopen #5641 : The formatting of self-closing tags in HTML5

    I know Prettier is opinionated, but I hope you might be willing to revisit something where common usage has changed. HTML5 was initially ambiguous regarding the use of trailing slashes on void (self-closing) elements, probably because some designers were coming from using XHTML and they wanted to reduce friction for them to make the transition. Adding the trailing slash was always optional.

    However, the need to ease the transition from XHTML is no longer the case and most people have moved on. In fact, the W3C Validator throws this warning:

    "Trailing slash on void elements has no effect and interacts badly with unquoted attribute values."

    HTML5 Bolierplate, which informs the VS Code HTML formatting style guidelines and is referenced by many designers and educators, doesn't use trailing slashes on void elements.

    Please consider rethinking this or at least provide a way to override it in VS Code.

  • 13

    Improve internal ESLint rule

    Description

    Checklist

    • [ ] I’ve added tests to confirm my change works.
    • [ ] (If changing the API or CLI) I’ve documented the changes I’ve made (in the docs/ directory).
    • [ ] (If the change is user-facing) I’ve added my changes to changelog_unreleased/*/XXXX.md file following changelog_unreleased/TEMPLATE.md.
    • [ ] I’ve read the contributing guidelines.

    Try the playground for this PR

  • 14

    Refactor `TSInterfaceBody` print

    Description

    TSInterfaceBody should use the same logic as ClassBody.

    To fix #14040, we can introduce similar logic as shouldPrintSemicolonAfterClassProperty after this get merged.

    //cc @thorn0

    Checklist

    • [ ] I’ve added tests to confirm my change works.
    • [ ] (If changing the API or CLI) I’ve documented the changes I’ve made (in the docs/ directory).
    • [ ] (If the change is user-facing) I’ve added my changes to changelog_unreleased/*/XXXX.md file following changelog_unreleased/TEMPLATE.md.
    • [ ] I’ve read the contributing guidelines.

    Try the playground for this PR

  • 15

    Handlebars: Improve HTML void element check

    Description

    Ref: https://github.com/prettier/prettier/pull/13691#discussion_r1001731467

    Checklist

    • [ ] I’ve added tests to confirm my change works.
    • [ ] (If changing the API or CLI) I’ve documented the changes I’ve made (in the docs/ directory).
    • [ ] (If the change is user-facing) I’ve added my changes to changelog_unreleased/*/XXXX.md file following changelog_unreleased/TEMPLATE.md.
    • [ ] I’ve read the contributing guidelines.

    Try the playground for this PR

  • 16

    Skip parsing inline javascript code in Less

    Description

    Closes #11340, since this feature already deprecated, I don't think changelog is necessary.

    Checklist

    • [ ] I’ve added tests to confirm my change works.
    • [ ] (If changing the API or CLI) I’ve documented the changes I’ve made (in the docs/ directory).
    • [ ] (If the change is user-facing) I’ve added my changes to changelog_unreleased/*/XXXX.md file following changelog_unreleased/TEMPLATE.md.
    • [ ] I’ve read the contributing guidelines.

    Try the playground for this PR

  • 17

    Resolves config by default in `getFileInfo()`

    Description

    Fixes #8581

    Checklist

    • [ ] I’ve added tests to confirm my change works.
    • [ ] (If changing the API or CLI) I’ve documented the changes I’ve made (in the docs/ directory).
    • [ ] (If the change is user-facing) I’ve added my changes to changelog_unreleased/*/XXXX.md file following changelog_unreleased/TEMPLATE.md.
    • [ ] I’ve read the contributing guidelines.

    Try the playground for this PR