Prettier is an opinionated code formatter.

Overview

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.

Comments
  • [resolved] [HTML] allow corresponding option to jsxBracketSameLine

    [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>
    
    type:option request lang:html 
    opened by bengry 292
  • Indent script and style tags content in *.vue files

    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>
    
    type:option request lang:vue locked-due-to-inactivity 
    opened by GrahamCampbell 229
  • Space after function name in declarations

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

    type:option request lang:typescript lang:javascript lang:flow status:wontfix 
    opened by justrhysism 207
  • Prettier 2.0 (old)

    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 () {}~

    type:meta area:cli area:api locked-due-to-inactivity 
    opened by azz 184
  • Markdown[next branch]: Do not insert spaces between Chinese/Japanese & latin letters

    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.

    opened by tats-u 178
  • Feature Request: breakBeforeElse

    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

    status:needs discussion type:option request 
    opened by vishnevskiy 173
  • feat: support HTML/Vue/Angular

    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.
    opened by ikatyang 164
  • Option to retain multi-line props in JSX/HTML

    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.

    status:needs discussion lang:jsx lang:html locked-due-to-inactivity 
    opened by damassi 152
  • Space after function keyword in anonymous functions

    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.

    lang:typescript lang:javascript lang:flow locked-due-to-inactivity 
    opened by lydell 146
  • Angular Output/Input decorators are moved to new line

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

    type:bug help wanted lang:javascript locked-due-to-inactivity 
    opened by bengry 110
  • Change HTML/JSX formatting to have one attribute/prop per line

    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:

    status:needs discussion lang:jsx lang:vue lang:html 
    opened by aboyton 107
  • WIP: alternative of #13995

    WIP: alternative of #13995

    Description

    alternative of #13995 Fix #13984

    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

    opened by sosukesuzuki 0
  • Treat `--trailing-comma=es5` as `all` when printing tuple types

    Treat `--trailing-comma=es5` as `all` when printing tuple types

    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

    opened by fisker 0
  • Flow: Print trailing comma in type parameters when `--trailing-comma=es5`

    Flow: Print trailing comma in type parameters when `--trailing-comma=es5`

    Description

    Fixes #3722

    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

    opened by fisker 0
  • Ugly formatting for `for...of` syntax with long function params

    Ugly formatting for `for...of` syntax with long function params

    Prettier 2.8.1 Playground link

    --parser babel
    

    Input:

    for (const key of Object.keys(loooooooooooooooooooooooooooooooooooooooooooonog)) {}
    

    Output:

    for (const key of Object.keys(
      loooooooooooooooooooooooooooooooooooooooooooonog
    )) {
    }
    
    

    Expected behavior:

    for (
      const key of Object.keys(loooooooooooooooooooooooooooooooooooooooooooonog)
    ) {}
    
    type:enhancement lang:javascript 
    opened by sosukesuzuki 0
  • Quote numeric keys for json-stringify parser

    Quote numeric keys for json-stringify parser

    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

    opened by fisker 0
  • Fix comments after directive

    Fix comments after directive

    Description

    Fixes #14080

    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

    opened by fisker 0
Releases(2.8.1)
Owner
Prettier
Prettier is an opinionated code formatter
Prettier
Detect copy-pasted and structurally similar code

Detect copy-pasted and structurally similar JavaScript code. Requires Node.js 6.0+, and supports ES6, JSX as well as Flow. Note: the project has been

Daniel St. Jules 3.5k Dec 26, 2022
Find and fix problems in your JavaScript code.

ESLint Website | Configuring | Rules | Contributing | Reporting Bugs | Code of Conduct | Twitter | Mailing List | Chat Room ESLint is a tool for ident

ESLint 21.9k Dec 31, 2022
The JavaScript Code Quality Tool

JSLint, The JavaScript Code Quality Tool Douglas Crockford [email protected] 2019-03-15 jslint.js contains the jslint function. It parses and a

Douglas Crockford 3.5k Jan 6, 2023
🌟 JavaScript Style Guide, with linter & automatic code fixer

JavaScript Standard Style Sponsored by English • Español (Latinoamérica) • Français • Bahasa Indonesia • Italiano (Italian) • 日本語 (Japanese) • 한국어 (Ko

Standard JS 27.8k Dec 31, 2022
Pre-evaluate code at build-time with babel-macros

preval.macro This is a babel-plugin-macros macro for babel-plugin-preval. Please see those projects for more information. Installation This module is

Kent C. Dodds 118 Dec 16, 2022
ECMAScript code beautifier/formatter

esformatter ECMAScript code beautifier/formatter. Important This tool is still missing support for many important features. Please report any bugs you

Miller Medeiros 968 Nov 1, 2022
All-in-one code linter and formatter for TypeScript and JavaScript

Uniform is a CLI tool - code linter and formatter for JavaScript and TypeScript. Works using eslint and prettier under the hood.

Irakli Dautashvili 21 Feb 27, 2022
A code formatter for the Motoko smart contract language.

Motoko Formatter · A Prettier plugin for the Motoko programming language. Setup After making sure Node.js is installed on your local machine, run the

DFINITY 25 Dec 19, 2022
A lightweight, locale aware formatter for strings containing unicode date tokens.

Date Token Format A lightweight (~2kB), locale aware formatter for strings containing unicode date tokens. Usage Install the package using: yarn add d

Donovan Hutchinson 1 Dec 24, 2021
A WASM shell parser and formatter with bash support, based on mvdan/sh

sh-syntax A WASM shell parser and formatter with bash support, based on mvdan/sh TOC Usage Install API Changelog License Usage Install # yarn yarn add

RxTS 7 Jan 1, 2023
Dead simple, single file, tiny byte formatter

tiny-byte-size Dead simple, no configuration needed, tiny byte formatter npm install tiny-byte-size Usage const byteSize = require('tiny-byte-size')

Mathias Buus 17 Aug 24, 2022
Runs prettier on a repository's code

prettier-docker-ga Run prettier on your code from Github workflows. Sample Github workflow (this assumes there is a prettier.config.js file in your re

Permafrost Software 2 Oct 18, 2022
Use pipeline to prettier code.

js-pipy Use pipeline to prettier code. Installation guide clone this repo locally npm i @htibor/js-pipy --save Usage const {pipy} = require('@htibor/j

Tibor Hegedűs 1 Feb 12, 2022
The official, opinionated, batteries-included toolset for efficient Redux development

Redux Toolkit The official, opinionated, batteries-included toolset for efficient Redux development (Formerly known as "Redux Starter Kit") Installati

Redux 9k Jan 8, 2023
🤠 An opinionated AJAX client for Ruby on Rails APIs

Rails Ranger Exploring the routes and paths of Ruby on Rails APIs Github Repository | Documentation Rails Ranger is a thin layer on top of Axios, whic

Victor Marques 37 Nov 22, 2022
:book: Opinionated CSS styleguide for scalable applications

css Opinionated CSS styleguide for scalable applications This guide was heavily inspired by experiments, awesome people like @fat and @necolas and awe

Guilherme Coelho 411 Nov 30, 2022
Highly opinionated project template for Serverless Framework that follows and applies hexagonal architecture principle to serverless world. Prepared with easy testing in mind.

serverless-hexagonal-template Highly opinionated project template for Serverless Framework that applies hexagonal architecture principles to the serve

Paweł Zubkiewicz 126 Dec 26, 2022
Clocklet - An opinionated clock-style vanilla-js timepicker.

An opinionated clock-style vanilla-js timepicker. Demo Features Keyboard and numpad friendly Autocomplete - e.g. "1"->"01:00", "12"->"12:00", "1234"->

31 Jun 7, 2022
This package includes some opinionated configuration for ESLint.

eslint-config-float This package includes some opinionated configuration for ESLint, used at Float and friends. Installation You can install and use t

Float 2 Jan 7, 2022
Opinionated syntax highlighting with shiki for markdown-it.

式神 shikigami Opinionated syntax highlighting with shiki for markdown-it. Installation Just use your favorite package manager. npm i @nrsk/shikigami Th

Vladislav Mamon 6 Sep 30, 2022