Prettier is an opinionated code formatter.

  • By Prettier
  • Last update: Nov 27, 2022
  • 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.

  • 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

    Update dependency ignore to v5.2.1

    Mend Renovate

    This PR contains the following updates:

    | Package | Change | Age | Adoption | Passing | Confidence | |---|---|---|---|---|---| | ignore | 5.2.0 -> 5.2.1 | age | adoption | passing | confidence |


    Release Notes

    kaelzhang/node-ignore

    v5.2.1

    Compare Source


    Configuration

    📅 Schedule: Branch creation - "after 01:00 on sunday" (UTC), Automerge - At any time (no schedule defined).

    🚦 Automerge: Disabled by config. Please merge this manually once you are satisfied.

    Rebasing: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

    🔕 Ignore: Close this PR and you won't be reminded about this update again.


    • [ ] If you want to rebase/retry this PR, check this box

    This PR has been generated by Mend Renovate. View repository job log here.

  • 13

    Update dependency esbuild to v0.15.16

    Mend Renovate

    This PR contains the following updates:

    | Package | Change | Age | Adoption | Passing | Confidence | |---|---|---|---|---|---| | esbuild | 0.15.15 -> 0.15.16 | age | adoption | passing | confidence |


    Release Notes

    evanw/esbuild

    v0.15.16

    Compare Source

    • Add a package alias feature (#​2191)

      With this release, you can now easily substitute one package for another at build time with the new alias feature. For example, --alias:oldpkg=newpkg replaces all imports of oldpkg with newpkg. One use case for this is easily replacing a node-only package with a browser-friendly package in 3rd-party code that you don't control. These new substitutions happen first before all of esbuild's existing path resolution logic.

      Note that when an import path is substituted using an alias, the resulting import path is resolved in the working directory instead of in the directory containing the source file with the import path. If needed, the working directory can be set with the cd command when using the CLI or with the absWorkingDir setting when using the JS or Go APIs.

    • Fix crash when pretty-printing minified JSX with object spread of object literal with computed property (#​2697)

      JSX elements are translated to JavaScript function calls and JSX element attributes are translated to properties on a JavaScript object literal. These properties are always either strings (e.g. in <x y />, y is a string) or an object spread (e.g. in <x {...y} />, y is an object spread) because JSX doesn't provide syntax for directly passing a computed property as a JSX attribute. However, esbuild's minifier has a rule that tries to inline object spread with an inline object literal in JavaScript. For example, x = { ...{ y } } is minified to x={y} when minification is enabled. This means that there is a way to generate a non-string non-spread JSX attribute in esbuild's internal representation. One example is with <x {...{ [y]: z }} />. When minification is enabled, esbuild's internal representation of this is something like <x [y]={z} /> due to object spread inlining, which is not valid JSX syntax. If this internal representation is then pretty-printed as JSX using --minify --jsx=preserve, esbuild previously crashed when trying to print this invalid syntax. With this release, esbuild will now print <x {...{[y]:z}}/> in this scenario instead of crashing.


    Configuration

    📅 Schedule: Branch creation - "after 01:00 on sunday" (UTC), Automerge - At any time (no schedule defined).

    🚦 Automerge: Disabled by config. Please merge this manually once you are satisfied.

    Rebasing: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

    🔕 Ignore: Close this PR and you won't be reminded about this update again.


    • [ ] If you want to rebase/retry this PR, check this box

    This PR has been generated by Mend Renovate. View repository job log here.

  • 14

    test: format instantiation expr in logical expr

    Description

    • added test for formating logical expression with instantiation expression (#13856)

    Close #13856

    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.
    • [x] I’ve read the contributing guidelines.

    Try the playground for this PR

  • 15

    Changed recommended way of creating a prettier config file

    Description

    This PR changes the recommended way to create a Prettier config file. We should use the power of autocomplete in current IDEs and this is made fairly easy in JavaScript. Other tools / frameworks use this as well, one example would be TailwindCSS

  • 16

    Skip measure width of last string in `printDocToString`

    Description

    Plugins like @prettier/plugin-pug prints a big string instead of doc commands, it cost time when measuring width. Ideally it should only measure the last line, or even better should measure from out when use the pos, we should improve it in future.

    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

    format vue template bug

    Prettier 2.8.0 Playground link https://www.prettier.cn/playground/#N4Igxg9gdgLgprEAuEAeAJgSwG4D4A6UABCUagE4QCu85AtADaZQDWBxpnGOuqA9FjyEufSjTj0mrdv0G4QAGhAQADjEzQAzslABDcpQDuABX0JtKXQ0O6AntqUAjcrrAs4MAMq6AtnAAyzHDIAGZWmnBOLm4eniquzADmyDDkVJEgcD6OcOjouf66UIlUuolwAGIQ5D66MOrFyCC6NBCKIAAWMD4MAOodmPCa8WBwnuaDOIO2TWCaDiDMEeQwxi6JtaHhGQBWmgAenkkMcACKVBDwWwwRSvHky03Y6e0q5MwwvZjoMB3IABwABjulAivRcKiabzgy2wwSUAEcLvA1qoLM1NHQoHBcrl2uQ4EjMAS1mVNkgwjcMhEfJgUmlqcczsjghTtkoYLpHF8fn8kAAmDkuTBSRIAYQgPnJmU0AFZ2lQIgAVLkWSm3EDPOAASSg+VgnjA7zUAEE9Z4YLYTtcIgBfW1AA

    # Options (if any):
    --parser : vue
    

    Input:

    <div>
        <router-link>
            <div></div>
        </router-link>
    </div>
    

    Output:

    SyntaxError: Unexpected closing tag "router-link". It may happen when the tag has already been closed by another tag. For more info see https://www.w3.org/TR/html5/syntax.html#closing-elements-that-have-implied-end-tags (4:5)
      2 |     <router-link>
      3 |         <div></div>
    > 4 |     </router-link>
        |     ^^^^^^^^^^^^^^
      5 | </div>
    

    Expected behavior: