Prettier 1.6: Config File, JSX
This release adds configuration file support to Prettier, as well as some significant enhancements to JSX printing.
I want to give a special shout out to @azz who has been maintaining the repository and implementing a bunch of the changes in this release as I had less time to devote to prettier due to vacation and switching team :)
Highlights
Configuration
#2434) by @azz
Implement cosmiconfig for workspace configuration (Since the very first release of prettier, people have asked for a .prettierrc
file. We've been trying to have as few options as possible and tried to avoid being one more .dotfile
that you have to have when starting a new project.
But, the truth is, we need to have some way to configure prettier that can be kept in sync with all the integrations. By not having one, we pushed the problem to them and saw a bunch of incompatible ways of handling the problem. So now, it's handled by prettier itself.
// .prettierrc
{
"trailingComma": "es5",
"singleQuote": true
}
For more information on configuration file support, see the README.
#2412) by @evilebottnawi
Support .prettierignore files (Along with telling what configuration to use, you can write a file .prettierignore
to tell which files not to convert.
## .prettierignore
dist/
package.json
JSX
#2398) by @suchipi
Improve JSX Formatting (The last big friction point from people trying to adopt prettier was around how JSX was being printed. We went through all the issues that were raised and made a bunch of changes:
- Arrow Function Expressions returning JSX will now add parens when the JSX breaks
// Before
const Component = props =>
<div>
Hello {props.name}!
</div>;
// After
const Component = props => (
<div>
Hello {props.name}!
</div>
);
- Conditional expressions within (or containing) JSX are formatted in a different way using parenthesis
// Before
<div>
{props.isVisible
? <BaseForm
url="/auth/google"
method="GET"
/>
: <Placeholder />}
</div>;
// After
<div>
{props.isVisible ? (
<BaseForm
url="/auth/google"
method="GET"
/>
) : (
<Placeholder />
)}
</div>
- JSX in logical expressions (|| or &&) is always wrapped in parens when the JSX breaks
// Before
<div>
{props.isVisible &&
<BaseForm
url="/auth/google"
method="GET"
/>}
</div>;
// After
<div>
{props.isVisible && (
<BaseForm
url="/auth/google"
method="GET"
/>
)}
</div>
Hopefully this is going to be more in line with how the majority of the community is writing JSX and we can have prettier be used in more place ;)
#2442) by @karl
Inline single expressions in JSX (With JSX, we started by respecting a lot of line breaks that were in the original source. This had the advantage of doing fewer changes to your codebase but chipped away the value of a consistent pretty printer as the same semantic code could be written in two ways.
During each new release we've tightened this and made decisions around how to always print a piece of code. The latest of those is what happens if there's a single child in a JSX object, we're now always going to inline it.
// Before
return (
<div>
{this.props.test}
</div>
);
return <div>{this.props.test}</div>;
// After
return <div>{this.props.test}</div>;
return <div>{this.props.test}</div>;
#2348) by @karl
Ensure there is a line break after leading JSX white space (Leading JSX empty spaces are now on their own line. It looked weird to have them before a tag as it "indented" it differently compared to the rest.
// Before
<span className="d1">
{' '}<a
href="https://github.schibsted.io/finn/troika"
className="link"
/>
</span>
// After
<span className="d1">
{' '}
<a
href="https://github.schibsted.io/finn/troika"
className="link"
/>
</span>
Other Changes
JSON
#2476) by @josephfrazier
Use babylon.parseExpression for JSON (We used to use a strict JSON parser that would throw if there was a comment or a trailing comma. This was inconvenient as many JSON files in practice are parsed using JavaScript or json5 that are not as strict. Now, we have relaxed this and are using the JavaScript parser to parse and print JSON. This means that comments will be maintained if there were some.
Note that this is purely additive, if your original file was JSON compliant, it will keep printing a valid JSON.
// Before
Syntax error
// After
{ /* some comment */ "a": 1 }
JavaScript
#2673) by @azz
Print 3 or more chained calls on multiple lines (This was a longstanding issue with the way we print long member chains. Prettier would try and cram all but the final callback onto one line, which reduced the readability. The solution we landed on was to always break over multiple lines if there are three or more function calls in a method chain.
// Before
Promise.resolve(0).catch(function(err) {}).then(function(res) {
//
});
// After
Promise.resolve(0)
.catch(function(err) {})
.then(function(res) {
//
});
#2423) by @azz
Add more supervisory parens (Parenthesis are a hot topic because they are not part of the AST, so prettier ignores all the ones you are putting and re-creating them from scratch. We went through all the things that people reported and came up with a few edge cases that were very confusing when comparisons were chained and %
was mixed with *
or /
.
One thing that we are not changing is the fact that we remove extra parenthesis around combinations of basic arithmetic operators: +-*/
.
// Before
x !== y === z;
x * y % z;
// After
(x !== y) === z;
(x * y) % z;
#2487) by @azz
Implement prettier-ignore inside JSX (It's useful to be able to ignore pieces of JSX, it's now possible to add a comment inside of a JSX expression to ignore the formatting of the next element.
// Before
<Component>
{/*prettier-ignore*/}
<span ugly format="" />
</Component>
// Before
<Component>
{/*prettier-ignore*/}
<span ugly format='' />
</Component>
#2664)
Do not swallow prettier-ignore comments (In order to support some edge cases, in the internals, we have the ability to avoid printing comments in a generic way and print them in the call site instead. It turns out that when we used prettier-ignore
, we didn't print the comments at all! This is now fixed.
// Before
push(
<td> :)
</td>,
);
// After
push(
// prettier-ignore
<td> :)
</td>,
);
#2359) by @jsnajdr
Fix indentation of a do-while condition (It took 6 months for someone to report that do-while were broken when the while condition is multi-line, it confirms my hunch that this construct is not widely used in practice.
// Before
do {} while (
someVeryLongFunc(
someVeryLongArgA,
someVeryLongArgB,
someVeryLongArgC
)
);
// After
do {} while (
someVeryLongFunc(
someVeryLongArgA,
someVeryLongArgB,
someVeryLongArgC
)
);
#2388) by @bakkot
Break sequence expressions (Another underused feature of JavaScript is sequence expressions. We used to do a bad job at printing them when they would go multi-line, this has been corrected :)
// Before
(a = b ? c : "lllllllllllllllllllllll"), (a = b
? c
: "lllllllllllllllllllllll"), (a = b ? c : "lllllllllllllllllllllll"), (a = b
? c
: "lllllllllllllllllllllll"), (a = b ? c : "lllllllllllllllllllllll");
// After
(a = b ? c : 'lllllllllllllllllllllll'),
(a = b ? c : 'lllllllllllllllllllllll'),
(a = b ? c : 'lllllllllllllllllllllll'),
(a = b ? c : 'lllllllllllllllllllllll'),
(a = b ? c : 'lllllllllllllllllllllll')
#2494) by @azz
Trim trailing whitespace from comments (We took the stance with prettier to remove all the trailing whitespaces. We used to not touch comments because it's user generated, but that doesn't mean that they should have whitespace :)
// Before
// There is some space here ->______________
// After
// There is some space here ->
#2660, #2661)
Fix interleaved comments in class decorators (Our handling for comments inside of the class declaration was very naive, we would just move all the comments to the top. We now are more precise and respect the comments that are interleaved inside of decorators and around extends
.
// Before
// A
// B
// C
@Foo()
@Bar()
class Bar {}
// After
// A
@Foo()
// B
@Bar()
// C
class Bar {}
#2493) by @azz
Improve bind expression formatting (Bind expressions are being discussed at TC39 and we figured we could print it with prettier. We used to be very naive about it and just chain it. Now, we use the same logic as we have for method chaining with the .
operator for it. We also fixed some edge cases where it would output invalid code.
// Before
observable::filter(data => data.someTest)::throttle(() =>
interval(10)::take(1)::takeUntil(observable::filter(data => someOtherTest))
)::map(someFunction);
// After
observable
::filter(data => data.someTest)
::throttle(() =>
interval(10)::take(1)::takeUntil(observable::filter(data => someOtherTest))
)
::map(someFunction);
#2570) by @existentialism
Add support for printing optional catch binding (It's being discussed at TC39 to be able to make the argument of a catch(e)
optional. Let's make sure we can support it in prettier if people use it.
// Before
Syntax error
// After
try {} catch {}
#2572) by @azz
Add support for printing optional chaining syntax (Another new proposal being discussed at TC39 is an optional chaining syntax. This is currently a stage 1 proposal, so the syntax may change at any time.
obj?.prop // optional static property access
obj?.[expr] // optional dynamic property access
func?.(...args) // optional function or method call
#2484) by @yangsu
Handle Closure Compiler type cast syntax correctly (Comments are tricky to get right, but especially when they have meaning based on where they are positioned. We're now special casing the way we deal with comments used as type cast for Closure Compiler such that they keep having the same semantics.
// Before
let assignment /** @type {string} */ = getValue();
// After
let assignment = /** @type {string} */ (getValue());
#2670) by @azz
Inline first computed property lookup in member chain (It looks kind of odd to have a computed property lookup on the next line, so we added a special case to inline it.
// Before
data
[key]('foo')
.then(() => console.log('bar'))
.catch(() => console.log('baz'));
// After
data[key]('foo')
.then(() => console.log('bar'))
.catch(() => console.log('baz'));
Flow
#2543, #2542) by @existentialism
Support opaque types and export star (The flow team introduced two very exciting features under a new syntax. We now support them in prettier. I've personally been waiting for opaque types for a veerrryyyy long time!
// Before
Syntax error
// After
opaque type ID = string;
export type * from "module";
#2643) by @jackyho112
Strip away unnecessary quotes in keys in type objects and interfaces (We've been doing this on JavaScript objects since the early days of prettier but forgot to apply the same thing to Flow and TypeScript types.
// Before
type A = {
"string": "A";
}
// After
type A = {
string: "A";
}
#2406) by @danwang
Print TypeParameter even when unary function type (Oopsy, we were dropping the generic in this very specific case.
// Before
type myFunction = A => B;
// After
type myFunction = <T>(A) => B;
#2561) by @azz
Keep parens around FunctionTypeAnnotation inside ArrayTypeAnnotation (Parenthesis... someday we'll get all of them fixed :)
// Before
const actionArray: () => void[] = [];
// After
const actionArray: (() => void)[] = [];
TypeScript
#2672) by @azz
Support TypeScript 2.5 RC (TypeScript 2.5 RC was recently announced, allowing you to use the upcoming "optional catch binding" syntax in TypeScript, too. 🎉
#2329) by @azz
Don't add namespace keyword to global declaration (// Before
namespace global {
export namespace JSX { }
}
// After
global {
export namespace JSX {}
}
#2472) by @backus
Fix <this.Component /> (Thanks to the untyped and permissive nature of JavaScript, we've been able to concat undefined to a string and get some interesting code as a result. Now fixed for this case :)
// Before
<undefined.Author />
// After
<this.Author />
#2439) by @azz
Allow type assertions to hug (We want to make sure that all the special cases that we added for JavaScript and Flow also work for TypeScript constructs. In this case, objects should also hug if they are wrapped in a as
operator.
// Before
const state = JSON.stringify(
{
next: window.location.href,
nonce,
} as State
);
// After
const state = JSON.stringify({
next: window.location.href,
nonce,
} as State);
#2419) by @azz
Remove parens for type assertions in binary expressions (Most of the time we add parenthesis for correctness but in this case, we added them for nothing, so we can just get rid of them and have a cleaner code :)
// Before
(<x>a) || {};
// After
<x>a || {};
#2525) by @azz
Print parens around type assertion as LHS in assignment (Yet another case of missing parenthesis. Thankfully we're getting very few of them nowadays and they are for extremely rare edge cases.
// Before
foo.bar as Baz = [bar];
// After
(foo.bar as Baz) = [bar];
#2574) by @existentialism
Print declare for TSInterfaceDeclaration (The declare
keyword doesn't do anything for interface
so we never put it there. However, it felt weird if you were in a declaration file and seeing everything have declare
before it except for interfaces. So now we reprint declare
if it was there in the first place.
// Before
interface Dictionary<T> {
[index: string]: T
}
// After
declare interface Dictionary<T> {
[index: string]: T
}
CSS
#2624) by @lydell
Normalize quotes in CSS (In order to get a first version of CSS to ship, we kept string quotes as is. We are now respecting the singleQuote
option of prettier. The difficulty here was to make sure that we output correct code for all the crazy escapes, unicode characters, emoji, special rules like charset which only work with double quotes...
// Before
div {
content: "abc";
}
// After
div {
content: 'abc';
}
#2627) by @lydell
Normalize numbers in CSS (Another place where we can reuse the logic we've done for JavaScript to improve CSS printing.
// Before
foo {
border: 1px solid rgba(0., 0.0, .0, .3);
}
// After
foo {
border: 1px solid rgba(0, 0, 0, 0.3);
}
#2644) by @lydell
Quote unquoted CSS attribute values in selectors (I can never quite remember the rules behind quotes around attributes so we're now always putting quotes there.
// Before
a[id=test] {}
// After
a[id="test"] {}
#2337) by @zanza00
Add support for css keyword (// Before
const header = css`.top-bar {background: black;margin: 0;position: fixed;}`
// After
const header = css`
.top-bar {
background: black;
margin: 0;
position: fixed;
}
`;
#2552, #2619) by @azz
Support styled-components with existing component (styled-components has a lot of different variants for tagging template literals as CSS. It's not ideal that we've got to encode all those ways inside of prettier but since we started, might as well do it for real.
styled(ExistingComponent)`
css: property;
`;
styled.button.attr({})`
border: rebeccapurple;
`;
#2411) by @azz
Trim whitespace in descendant combinator (The CSS parsers we use do not give us a 100% semantic tree: in many occasions they bail and just give us what is being entered. It's up to us to make sure we clean this up while maintaining correctness. In this case, we just printed spaces between selectors as is but we know it's correct to always replace it by a single space.
// Before
.hello
.how-you-doin {
height: 42;
}
// After
.hello .how-you-doin {
height: 42;
}
#2373) by @azz
Strip BOM before parsing (I still have nightmares from dealing with BOM in a previous life. Thankfully, in 2017 it's no longer a big issue as most tooling is now aware of it. Thanks @azz for fixing an edge cases related to CSS parsing.
// Before
[BOM]/* Block comment *
html {
content: "#{1}";
}
// After
[BOM]/* Block comment */
html {
content: "#{1}";
}
GraphQL
#2319) by @josephfrazier
Add support for range-formatting GraphQL (If you tried to use the range formatting feature in a GraphQL file, it would throw an exception, now it properly worked again and only reformats the piece you selected.
.gql
file extension to be parsed as GraphQL (#2357) by @rrdelaney
Add At Facebook, we use .graphql
extension but it looks like it's common to have .gql
as well, doesn't cost a lot to support it in the heuristic that figures out what parser to use.
CLI
#2356) by @evilebottnawi
Support multiple patterns with ignore pattern (It was already possible to have multiple glob patterns but they would be additive, with this change, you can add a glob pattern to ignore some files. It should be very handy to ignore folders that are deeply nested.
prettier --write '{**/*,*}.{js,jsx,json}' '!vendor/**'
#2393) by @josephfrazier
Make --list-different to work with --stdin (This is a handy way of knowing if prettier would print a piece of code in a different way. We already had all the concepts in place, we just needed to wire them up correctly.
$ echo 'call ( ) ;' | prettier --list-different
(stdin)
$ echo $?
1