* Add test with unnecessarily escaped non-quote character In https://github.com/prettier/prettier/pull/1571/commits/0b6d19db18cd64f5d191f8c01dea3ea5525503b3, I noticed that `makeString` doesn't unescape unnecessarily escaped non-quote characters. This change simply adds a test for that. * Fix test with unnecessarily escaped non-quote character Unfortunately, this breaks a couple of other tests... * Revert "Fix test with unnecessarily escaped non-quote character" See https://github.com/prettier/prettier/pull/1575#issuecomment-300490172 This reverts commit d05652518fe7d4e2fb82ce48ffc922b153de5593. * Unescape unnecessarily escaped characters in strings * Add test for unnecessarily escaped character at not-beginning of string * Fix test for unnecessarily escaped character at not-beginning of string * Add test for multiple unnecessary escapes in strings * Pass test for multiple unnecessary escapes in strings * Add test for octal escapes in strings See https://github.com/prettier/prettier/pull/1575#discussion_r115804065 * Pass test for octal escapes in strings See https://github.com/prettier/prettier/pull/1575#discussion_r115804065 * Add test for unnecessarily escaped character preced by escaped backslash See https://github.com/prettier/prettier/pull/1575#discussion_r115804065 * Pass test for unnecessarily escaped character preced by escaped backslash This just allows an even number of backslashes to precede the unnecessary one. See https://github.com/prettier/prettier/pull/1575#discussion_r115804065 * Add test for unescaped character after escaped backslash in strings * Add test for unescaped character preceded by two escaped backslashes in string See https://github.com/prettier/prettier/pull/1575#discussion_r115808571 * Pass test for unescaped character preceded by two escaped backslashes in string This breaks another test though... See https://github.com/prettier/prettier/pull/1575#discussion_r115808571 * Update snapshot It turns out the test wasn't broken, I had just flubbed the escaping in the snapshot. The easiest way to see that this actually works is ```bash $ cat | prettier --stdin "hol\\a (the a is not escaped)" // press Control-D after the newline "hol\\a (the a is not escaped)"; // press Control-D after the newline ``` * Prevent test strings from being parsed as directives See https://github.com/prettier/prettier/pull/1575#discussion_r115820336 (cherry picked from commit 126e56ab2c79801cbf7fee22189212d8c93581df) * Add test for consecutive unnecessarily escaped characters in strings See https://github.com/prettier/prettier/pull/1575#discussion_r115822286 * Pass test for consecutive unnecessarily escaped characters in strings See https://github.com/prettier/prettier/pull/1575#discussion_r115822286 This looping is hacky. We might be able to emulate lookbehind instead. * Optimize (maybe?) string unescaping loop Not sure how expensive string comparison is here... See https://github.com/prettier/prettier/commit/2323c8c025e5302995b2846ed45fd0bd67e66f1b#commitcomment-22092267 * Safeguard against string unescaping loop hanging See https://github.com/prettier/prettier/pull/1575#discussion_r115827531 * Add more comprehensive tests for unnecessary string escapes See https://github.com/prettier/prettier/pull/1575#discussion_r115798155 * Remove superfluous variables from makeString() See https://github.com/prettier/prettier/pull/1575#discussion_r115834468 * Unescape unnecessary strings escapes without looping * Unescape unnecessary string escapes while handling quotes Kudos to @lydell for figuring this out! See https://github.com/prettier/prettier/pull/1575/files#r115860741 * Test that unnecessary escapes remain in directive literals See: * https://github.com/prettier/prettier/pull/1575#discussion_r115820336 * https://github.com/prettier/prettier/pull/1575#issuecomment-300633277
Prettier
Prettier is an opinionated JavaScript formatter inspired by refmt with advanced support for language features from ES2017, JSX, and Flow. It removes all original styling and ensures that all outputted JavaScript conforms to a consistent style. (See this blog post)
If you are interested in the details, you can watch those two conference talks:
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 widths, 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 width into account, wrapping code when necessary.
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.)
In the future we will have better support for formatting whole projects.
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.
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.
1. lint-staged
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.
2. pre-commit
Just 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.1.0']
Find more info from here
3. bash script
Alternately you can just 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 two functions, exported as format and check. 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.
Options
Prettier ships with a handful of customizable format options, usable in both the CLI and API.
| Option | Default | CLI override | API override |
|---|---|---|---|
| Tabs - Indent lines with tabs instead of spaces. | false |
--use-tabs |
useTabs: <bool> |
| Print Width - Specify the length of line that the printer will wrap on. | 80 |
--print-width <int> |
printWidth: <int> |
| Tab Width - Specify the number of spaces per indentation-level. | 2 |
--tab-width <int> |
tabWidth: <int> |
| Quotes - Use single quotes instead of double quotes. | 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) |
"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> |
| Parser - Specify which parse to use. | babylon |
--parser <flow|babylon> |
parser: "<flow|babylon>" |
| 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> |
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 directory for on-demand formatting.
Vim
Add sbdchd/neoformat to your list based on the tool you use:
Plug 'sbdchd/neoformat'
Then make Neoformat run on save:
autocmd BufWritePre *.js Neoformat
Other autocmd events
You can also make Vim format your code more frequently, by setting an autocmd for other events. Here are a couple of useful ones:
TextChanged: after a change was made to the text in Normal modeInsertLeave: when leaving Insert mode
For example, you can format on both of the above events together with BufWritePre like this:
autocmd BufWritePre,TextChanged,InsertLeave *.js Neoformat
See :help autocmd-events in Vim for details.
Customizing Prettier in Vim
If your project requires settings other than the default Prettier settings, you can pass arguments to do so in your .vimrc or vim project, you can do so:
autocmd FileType javascript setlocal formatprg=prettier\ --stdin\ --parser\ flow\ --single-quote\ --trailing-comma\ es5
" Use formatprg when available
let g:neoformat_try_formatprg = 1
Each option needs to be escaped with \.
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.
JetBrains
JetBrains users can configure prettier as an External Tool.
See this blog post or this
directory with examples.
More editors are coming soon.
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.
Related Projects
eslint-plugin-prettierplugs Prettier into your ESLint workfloweslint-config-prettierturns off all ESLint rules that are unnecessary or might conflict with Prettierprettier-eslintpassesprettieroutput toeslint --fixprettier-standardusesprettierandprettier-eslintto format code with standard rulesprettier-standard-formatterpassesprettieroutput tostandard --fixprettier-miscellaneousprettierwith a few minor extra optionsneutrino-preset-prettierallows you to use Prettier as a Neutrino presetprettier_druns Prettier as a server to avoid Node.js startup delay
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. Better docs will come soon.
Badge
Show the world you're using Prettier →
[](https://github.com/prettier/prettier)
Contributing
To get up and running, install the dependencies and run the tests:
yarn
yarn test
Here's what you need to know about the tests:
- The tests uses Jest snapshots.
- You can make changes and run
jest -u(oryarn test -- -u) to update the snapshots. Then rungit diffto take a look at what changed. Always update the snapshots when opening a PR. - You can run
AST_COMPARE=1 jestfor a more robust test run. That formats each file, re-parses it, and compares the new AST with the original one and makes sure they are semantically equivalent. - Each test folder has a
jsfmt.spec.jsthat runs the tests. Normally you can just putrun_spec(__dirname);there. You can also pass options and additional parsers, like this:run_spec(__dirname, { trailingComma: "es5" }, ["babylon"]); tests/flow/contains the Flow test suite, and is not supposed to be edited by hand. To update it, clone the Flow repo next to the Prettier repo and run:node scripts/sync-flow-tests.js ../flow/tests/.- If you would like to debug prettier locally, you can either debug it in node
or the browser. The easiest way to debug it in the browser is to run the
interactive
docsREPL locally. The easiest way to debug it in node, is to create a local test file and run it in an editor like VS Code.
If you can, take look at commands.md and check out Wadler's paper to understand how Prettier works.

