/prettier

Prettier is an opinionated code formatter.

Primary LanguageJavaScriptMIT LicenseMIT

Prettier

Gitter Build Status NPM version

Table of Contents

Prettier is an opinionated code formatter inspired by refmt with advanced support for language features from:

It removes all original styling* and ensures that all outputted code conforms to a consistent style. (See this blog post)

If you are interested in the details, you can watch those two conference talks:

In the case of JavaScript, this goes way beyond ESLint and other projects built on it. Unlike ESLint, there aren't a million configuration options and rules. But more importantly: everything is fixable. This works because Prettier never "checks" anything; it takes JavaScript as input and delivers the formatted JavaScript as output.

In technical terms: Prettier parses your JavaScript into an AST (Abstract Syntax Tree) and pretty-prints the AST, completely ignoring any of the original formatting*. Say hello to completely consistent syntax!

There's an extremely important piece missing from existing styling tools: the maximum line length. Sure, you can tell ESLint to warn you when you have a line that's too long, but that's an after-thought (ESLint never knows how to fix it). The maximum line length is a critical piece the formatter needs for laying out and wrapping code.

For example, take the following code:

foo(arg1, arg2, arg3, arg4);

That looks like the right way to format it. However, we've all run into this situation:

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

Suddenly our previous format for calling function breaks down because this is too long. What you would probably do is this instead:

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

This clearly shows that the maximum line length has a direct impact on the style of code we desire. The fact that current style tools ignore this means they can't really help with the situations that are actually the most troublesome. Individuals on teams will all format these differently according to their own rules and we lose the consistency we sought after.

Even if we disregard line lengths, it's too easy to sneak in various styles of code in all other linters. The most strict linter I know happily lets all these styles happen:

foo({ num: 3 },
  1, 2)

foo(
  { num: 3 },
  1, 2)

foo(
  { num: 3 },
  1,
  2
)

Prettier bans all custom styling* by parsing it away and re-printing the parsed AST with its own rules that take the maximum line length into account, wrapping code when necessary.

*Well actually, some original styling is preserved when practical—see empty lines and multi-line objects.

Usage

Install:

yarn add prettier --dev

You can install it globally if you like:

yarn global add prettier

We're defaulting to yarn but you can use npm if you like:

npm install [-g] prettier

CLI

Run Prettier through the CLI with this script. Run it without any arguments to see the options.

To format a file in-place, use --write. You may want to consider committing your code before doing that, just in case.

prettier [opts] [filename ...]

In practice, this may look something like:

prettier --single-quote --trailing-comma es5 --write "{app,__{tests,mocks}__}/**/*.js"

Don't forget the quotes around the globs! The quotes make sure that Prettier expands the globs rather than your shell, for cross-platform usage. The glob syntax from the glob module is used.

Prettier CLI will ignore files located in node_modules directory. To opt-out from this behavior use --with-node-modules flag.

If you're worried that Prettier will change the correctness of your code, add --debug-check to the command. This will cause Prettier to print an error message if it detects that code correctness might have changed. Note that --write cannot be used with --debug-check.

Another useful flag is --list-different (or -l) which prints the filenames of files that are different from Prettier formatting. If there are differences the script errors out, which is useful in a CI scenario.

prettier --single-quote --list-different "src/**/*.js"

Pre-commit hook for changed files

You can use this with a pre-commit tool. This can re-format your files that are marked as "staged" via git add before you commit.

Install it along with husky:

yarn add lint-staged husky --dev

and add this config to your package.json:

{
  "scripts": {
    "precommit": "lint-staged"
  },
  "lint-staged": {
    "*.js": [
      "prettier --write",
      "git add"
    ]
  }
}

See https://github.com/okonet/lint-staged#configuration for more details about how you can configure lint-staged.

Copy the following config in your pre-commit config yaml file:

    -   repo: https://github.com/awebdeveloper/pre-commit-prettier
        sha: ''  # Use the sha or tag you want to point at
        hooks:
        -   id: prettier
            additional_dependencies: ['prettier@1.4.2']

Find more info from here.

3. bash script

Alternately you can save this script as .git/hooks/pre-commit and give it execute permission:

#!/bin/sh
jsfiles=$(git diff --cached --name-only --diff-filter=ACM | grep '\.jsx\?$' | tr '\n' ' ')
[ -z "$jsfiles" ] && exit 0

diffs=$(node_modules/.bin/prettier -l $jsfiles)
[ -z "$diffs" ] && exit 0

echo "here"
echo >&2 "Javascript files must be formatted with prettier. Please run:"
echo >&2 "node_modules/.bin/prettier --write "$diffs""

exit 1

API

The API has three functions, exported as format, check, and formatWithCursor. format usage is as follows:

const prettier = require("prettier");

const options = {} // optional
prettier.format(source, options);

check checks to see if the file has been formatted with Prettier given those options and returns a Boolean. This is similar to the --list-different parameter in the CLI and is useful for running Prettier in CI scenarios.

formatWithCursor both formats the code, and translates a cursor position from unformatted code to formatted code. This is useful for editor integrations, to prevent the cursor from moving when code is formatted. For example:

const prettier = require("prettier");

prettier.formatWithCursor(" 1", { cursorOffset: 2 });
// -> { formatted: '1;\n', cursorOffset: 1 }

Options

Prettier ships with a handful of customizable format options, usable in both the CLI and API.

Option Default CLI override API override
Print Width - Specify the length of line that the printer will wrap on.

We strongly recommend against using more than 80 columns. Prettier works by craming as much content as possible until it reaches the limit, which happens to work well for 80 columns but makes lines that are very crowded. When a bigger column count is used in styleguides, it usually means that code is allowed to go beyond 80 columns, but not to make every single line go there, like prettier would do.
80 --print-width <int> printWidth: <int>
Tab Width - Specify the number of spaces per indentation-level. 2 --tab-width <int> tabWidth: <int>
Tabs - Indent lines with tabs instead of spaces. false --use-tabs useTabs: <bool>
Semicolons - Print semicolons at the ends of statements.

Valid options:
- true - add a semicolon at the end of every statement
- false - only add semicolons at the beginning of lines that may introduce ASI failures
true --no-semi semi: <bool>
Quotes - Use single quotes instead of double quotes.

Notes:
- Quotes in JSX will always be double and ignore this setting.
- If the number of quotes outweighs the other quote, the quote which is less used will be used to format the string - Example: "I'm double quoted" results in "I'm double quoted" and "This \"example\" is single quoted" results in 'This "example" is single quoted'.
false --single-quote singleQuote: <bool>
Trailing Commas - Print trailing commas wherever possible.

Valid options:
- "none" - no trailing commas
- "es5" - trailing commas where valid in ES5 (objects, arrays, etc)
- "all" - trailing commas wherever possible (function arguments). This requires node 8 or a transform.
"none" --trailing-comma <none|es5|all> trailingComma: "<none|es5|all>"
Bracket Spacing - Print spaces between brackets in object literals.

Valid options:
- true - Example: { foo: bar }
- false - Example: {foo: bar}
true --no-bracket-spacing bracketSpacing: <bool>
JSX Brackets on Same Line - Put the > of a multi-line JSX element at the end of the last line instead of being alone on the next line false --jsx-bracket-same-line jsxBracketSameLine: <bool>
Cursor Offset - Specify where the cursor is. This option only works with prettier.formatWithCursor, and cannot be used with rangeStart and rangeEnd. -1 --cursor-offset <int> cursorOffset: <int>
Range Start - Format code starting at a given character offset. The range will extend backwards to the start of the first line containing the selected statement. This option cannot be used with cursorOffset. 0 --range-start <int> rangeStart: <int>
Range End - Format code ending at a given character offset (exclusive). The range will extend forwards to the end of the selected statement. This option cannot be used with cursorOffset. Infinity --range-end <int> rangeEnd: <int>
Parser - Specify which parser to use. Both the babylon and flow parsers support the same set of JavaScript features (including Flow). Prettier automatically infers the parser from the input file path, so you shouldn't have to change this setting. babylon --parser <flow|babylon|typescript|postcss> parser: "<flow|babylon|typescript|postcss>"
Filepath - Specify the input filepath this will be used to do parser inference.

Example:
cat foo | prettier --stdin-filepath foo.css
will default to use postcss parser
--stdin-filepath filepath: <string>

Excluding code from formatting

A JavaScript comment of // prettier-ignore will exclude the next node in the abstract syntax tree from formatting.

For example:

matrix(
  1, 0, 0,
  0, 1, 0,
  0, 0, 1
)

// prettier-ignore
matrix(
  1, 0, 0,
  0, 1, 0,
  0, 0, 1
)

will be transformed to:

matrix(1, 0, 0, 0, 1, 0, 0, 0, 1);

// prettier-ignore
matrix(
  1, 0, 0,
  0, 1, 0,
  0, 0, 1
)

Editor Integration

Atom

Atom users can simply install the prettier-atom package and use Ctrl+Alt+F to format a file (or format on save if enabled).

Emacs

Emacs users should see this repository for on-demand formatting.

Vim

Vim users can simply install either sbdchd/neoformat or mitermayer/vim-prettier, for more details see see this directory

Visual Studio Code

Can be installed using the extension sidebar. Search for Prettier - JavaScript formatter.

Can also be installed using ext install prettier-vscode.

Check its repository for configuration and shortcuts

Visual Studio

Install the JavaScript Prettier extension.

Sublime Text

Sublime Text support is available through Package Control and the JsPrettier plug-in.

WebStorm

See the WebStorm guide.

Language Support

Prettier attempts to support all JavaScript language features, including non-standardized ones. By default it uses the Babylon parser with all language features enabled, but you can also use the Flow parser with the parser API or --parser CLI option.

All of JSX and Flow syntax is supported. In fact, the test suite in tests is the entire Flow test suite and they all pass.

Prettier also supports TypeScript, CSS, LESS, and SCSS.

The minimum version of TypeScript supported is 2.1.3 as it introduces the ability to have leading | for type definitions which prettier outputs.

Related Projects

Technical Details

This printer is a fork of recast's printer with its algorithm replaced by the one described by Wadler in "A prettier printer". There still may be leftover code from recast that needs to be cleaned up.

The basic idea is that the printer takes an AST and returns an intermediate representation of the output, and the printer uses that to generate a string. The advantage is that the printer can "measure" the IR and see if the output is going to fit on a line, and break if not.

This means that most of the logic of printing an AST involves generating an abstract representation of the output involving certain commands. For example, concat(["(", line, arg, line ")"]) would represent a concatentation of opening parens, an argument, and closing parens. But if that doesn't fit on one line, the printer can break where line is specified.

More (rough) details can be found in commands.md.

Badge

Show the world you're using Prettierstyled with prettier

[![styled with prettier](https://img.shields.io/badge/styled_with-prettier-ff69b4.svg)](https://github.com/prettier/prettier)

Contributing

See CONTRIBUTING.md.