Closed greenkeeper[bot] closed 7 years ago
Merging #176 into master will not change coverage. The diff coverage is
n/a
.
@@ Coverage Diff @@
## master #176 +/- ##
=======================================
Coverage 92.91% 92.91%
=======================================
Files 9 9
Lines 240 240
=======================================
Hits 223 223
Misses 17 17
Continue to review full report at Codecov.
Legend - Click here to learn more
Ξ = absolute <relative> (impact)
,ΓΈ = not affected
,? = missing data
Powered by Codecov. Last update 4b91ec0...004f2b2. Read the comment docs.
Update to this version instead π
The new version differs by 12 commits .
ad637d0
1.1.0
17051ec
[WIP] no-semi comments (#1257)
088754f
Fixing n.comments check in printer (#1239)
6a259b6
Get rid of fixFaultyLocations code (#1252)
9d616fc
Remove trailing whitespace (#1259)
61183f8
Use a whitelist instead of blacklist for member breaking (#1261)
2078225
Fix flow union params (#1251)
97c662b
Do not inline member expressions as part of assignments (#1256)
1802545
Document debugging strategies (#1253)
19b7feb
Fix : ReferenceError: err is not defined (#1254)
6ecbb99
fix small typo (#1255)
d39654f
[1242]: Prettier 1.0 is the stabler release we've been waiting for (#1243)
See the full diff.
Update to this version instead π
The new version differs by 26 commits .
bc53920
1.2.0
3dc7562
Don't inline paren at right of arguments (#1345)
aafcf5f
Break if () if conditional inside breaks (#1344)
042e603
Fix arrow function parenthesis with comments in flow (#1339)
938f0e3
Improve regex printing (#1341)
e2fbaaf
Update link to @vjeux's React London presentation (#1330)
706640d
Optimize prettier --help
for humans (#1340)
cb79d82
add printer branch for TSFirstTypeNode (#1332)
dc499ba
Add information about Vim's other autocmd events (#1333)
565106d
Add parentheses for assignment as body of arrow (#1326)
652e2f9
Add prettier_d to Related Projects (#1328)
2e613cb
Add jestbrains filewatcher docs (#1310)
5e7503d
Add typescript as a valid parser value (#1318)
8d03423
Avoid breaking arguments for last arg expansion (#1305)
5995af2
Bail when traversing === groups (#1294)
There are 26 commits in total. See the full diff.
Update to this version instead π
The reason why I (@vjeux) embarked on this journey working on prettier has always been to get the entire Facebook codebase converted over. I would like to give an update on how it is going and what is the process to get there.
The first projects to adopt prettier were Jest, React and immutable-js. Those are small codebases in the order of hundreds of files that have their own infrastructure. There are 5 or less people working on them full time.
Then, Oculus and Nuclide converted their codebase over. The scale is bigger with a few thousands of files and tens of full time contributors but looks pretty similar to the first projects. The conversions went in one big codemod and that's it.
Now, the entire Facebook codebase is way bigger than this and it's not feasible to just convert everything in one go and to convince everyone that their entire codebase is going to be reformatted under their feet. So we need to find a more incremental approach.
Running prettier on a piece of code is a pretty expensive operation, it makes your pull request look bad because of a lot of unrelated changes and it causes merge conflicts for all the outstanding pull requests. So once a file has been formatted, you should do everything to make sure it remains formatted.
@format
to the first block comment like @flow
.@format
is present.
@format
to the header.@format
header.@format
is in the header.@format
in order to avoid getting warnings afterwards.@format
over time.We finally got all those things wired up 1.5 weeks ago and the reception has been insane. Many people from various teams converted their codebase to prettier on their own. As of today, 15% of Facebook codebase has been converted over!
When I started working on prettier, I had a hunch that people were hungry for tools to solve formatting. But I had no idea that once the tooling was in place, people would rush to convert their codebase over! This is great confirmation that this project is useful to people and not just a gimmicky tool.
@despairblue, @azz and @JamesHenry have been hard at work around getting TypeScript supported by prettier as it's the top requested feature. 2000 out of 11000 files in the TypeScript test suite are not yet properly printed. You can follow progress on #1480 and do not hesitate to help out!
The --trailing-comma=all
option is supposed to add trailing commas everywhere possible, but as an oversight we forgot to do it for flow generics.
// Before
type Errors = Immutable.Map<
Ahohohhohohohohohohohohohohooh,
Fbt | Immutable.Map<ErrorIndex, Fbt>
>;
// After
type Errors = Immutable.Map<
Ahohohhohohohohohohohohohohooh,
Fbt | Immutable.Map<ErrorIndex, Fbt>,
>;
The phase after printing things correctly is to tweak the output to make it closer to the way people write code in practice. Inlining optional flow types is a small thing that makes a difference.
// Before
type Cursor = Promise<
?{
newCursor?: number,
formatted: string,
}
>;
// After
type Cursor = Promise<?{
newCursor?: number,
formatted: string,
}>;
We can always find more places to add breaks when things don't fit 80 columns. This time it's around declaring a type as a constant string.
// Before
export type AdamPlacementValidationSingleErrorKey = 'SOME_FANCY_TARGETS.GLOBAL_TARGET';
// After
export type AdamPlacementValidationSingleErrorKey =
'SOME_FANCY_TARGETS.GLOBAL_TARGET';
=
for flow generics default arguments (#1476)Another example of small thing where we can improve the display of flow code. For function default arguments we put a space around =
but didn't around flow generics.
// Before
class PolyDefault<T=string> {}
// After
class PolyDefault<T = string> {}
I'm trying to figure out something to write here, but ... it just looks weird!
// Before
const selectorByPath:
Path
=> SomethingSelector<
SomethingUEditorContextType,
SomethingUEditorContextType,
SomethingBulkValue<string>
> = memoizeWithArgs(/* ... */)
// After
const selectorByPath: Path => SomethingSelector<
SomethingUEditorContextType,
SomethingUEditorContextType,
SomethingBulkValue<string>
> = memoizeWithArgs(/* ... */);
We were a bit too lenient around parenthesis for optional flow types. In one case in the entire Facebook codebase, it generated code with different semantics. As part of this fix, we hardened the list of types that can be written without parenthesis.
// Before
type X = ?(number, number) => number => void;
// After
type X = (?(number, number) => number) => void;
It is a parse error to add a trailing comma without parenthesis for arguments of arrow function types. We found one case in Facebook codebase when this happened, it's a very rare occurrence.
// Before
type IdeConnectionFactory =
child_process$ChildProcess,
=> FlowIDEConnection = defaultIDEConnectionFactory;
// After
type IdeConnectionFactory =
child_process$ChildProcess,
=> FlowIDEConnection = defaultIDEConnectionFactory;
This one is an example where the way the AST is structured is not our favor. Instead of having a list of elements inside of a type, the AST is structured in a way where normal keys and array keys each have their own group. In order to restore the initial order, we're now reading from the original source :(
// Before
type Foo = {
[key: string]: void,
alpha: "hello",
beta: 10
};
// After
type Foo = {
alpha: 'hello',
[key: string]: void,
beta: 10
}
A long standing issue with template literals and prettier is around the indentation of code inside of ${}
. It used to be the indentation of the backtick but turned out to give poor results. Instead people tend to use the indent of the ${
. We changed this behavior and it magically made GraphQL queries look pretty!
// Before
Relay.createContainer({
nodes: ({ solution_type, time_frame }) => Relay.QL`
fragment {
__typename
${OptimalSolutionsSection.getFragment("node", {
solution_type,
time_frame
})}
}
`
})
// After
Relay.createContainer({
nodes: ({ solution_type, time_frame }) => Relay.QL`
fragment {
__typename
${OptimalSolutionsSection.getFragment("node", {
solution_type,
time_frame
})}
}
`
})
Template literals are very hard to deal with for a pretty printer because the spaces inside are meaningful so you can't re-indent them. We didn't know what to do for a call with a single template literal so we didn't do anything, but we kept receiving reports of people saying that prettier indented it the wrong way, so we are now inlining them. Fingers crossed it is going to cover most use cases.
// Before
insertRule(
`*, *:before, *:after {
box-sizing: inherit;
}`
);
// After
insertRule(`*, *:before, *:after {
box-sizing: inherit;
}`);
We manipulate line endings in a lot of places in prettier and took great care of handling both \n
and \r\n
except for template literals where we forgot. Now this is fixed!
// Before
const aLongString = `
Line 1
Line 2
Line 3
`;
// After
const aLongString = `
Line 1
Line 2
Line 3
`;
We already inline template literals that are tagged (eg graphql`query`
) but didn't for plain template literals. For the anecdote, it turns out the code was supposed to support it but it was using TemplateElement
instead of TemplateLiteral
:(
// Before
const inlineStore = preloadedState =>
`
<script>
window.preloadedState = ${JSON.stringify(preloadedState).replace(/</g, '\\u003c')}
</script>
`
// After
const inlineStore = preloadedState => `
<script>
window.preloadedState = ${JSON.stringify(preloadedState).replace(/</g, '\\u003c')}
</script>
`
While working on printing nested ternaries, everyone focused on the ones with the shape of an if then else cond1 ? elem1_if : cond2 ? elem2_if : elem_else
which is the most common. But, if you move move some ?
and :
around you can have another pattern. It looks almost the same but has a different meaning. In order to reduce confusion, we're adding parenthesis around the uncommon form.
// Before
cond1 ? cond2 ? elem2_if : elem2_else : elem1_else
// After
cond1 ? (cond2 ? elem2_if : elem2_else) : elem1_else
There's an eslint rule no-confusing-arrows
which suggests adding parenthesis for ternaries in arrow functions without brackets.
var x = a => 1 ? 2 : 3;
var x = a <= 1 ? 2 : 3;
It makes sense when code is in one line, but when it is split into multiple lines, the parenthesis are unnecessary given the indentation, so we now only put them when they serve their disambiguation purpose.
// Before
var x = a => (1 ? 2 : 3);
var x = a =>
(1
? 2
: 3);
// After
var x = a => (1 ? 2 : 3);
var x = a =>
1
? 2
: 3;
This one was often requested for React Stateless Functional Components (SFC). If you make use of a lot of them, it's likely going to be a big change for you.
// Before
const X = (
props: {
a: boolean,
},
) => <div />;
// After
const X = (props: {
a: boolean,
}) => <div />;
One thing we discovered early on is that people usually break the arguments of the function before breaking the return type. Unfortunately, the code responsible to inline single destructuring argument broke that assumption and it introduced bad looking code like this example. The good news is that it enables us to turn on inlining for single arguments that are typed with an object.
// Before
class X {
async onDidInsertSuggestion({editor, triggerPosition, suggestion}): Promise<
void
> {
}
}
// After
class X {
async onDidInsertSuggestion({
editor,
triggerPosition,
suggestion
}): Promise<void> {
}
}
This one has been a long standing issue and is an easy fix, but was an invaluable tool: whenever someone reported that []
or {}
would break, we were able to fix the example by fixing something else. So it was a great way to surface edge cases. Fortunately, this vein has now ran out and all the recent examples just look bad with no other reason than the fact that they are breaking. So it's time to finally do it!
// Before
const a = someVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeLong.Expression || [
];
// After
const a = someVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeLong.Expression || [];
We have a lot of issues where code breaks in array access when it doesn't look good. We don't yet have a good generic solution for it, but we can add a specific fix a common situation: [0]
.
// Before
queryThenMutateDOM(() => {
title = SomeThing.call(root, "someLongStringThatPushesThisTextReall")[
0
];
});
// After
queryThenMutateDOM(() => {
title = SomeThing.call(
root,
"someLongStringThatPushesThisTextReall",
)[0];
});
We were not using the correct indentation logic for do-while condition but someone noticed, now we do!
// Before
do {}
while (someVeryLongStringA && someVeryLongStringB && someVeryLongStringC && someVeryLongStringD);
// After
do {}
while (
someVeryLongStringA &&
someVeryLongStringB &&
someVeryLongStringC &&
someVeryLongStringD
);
We forgot to add one case in the comment detection code when they appear last for JSX attributes and function arguments which made them go after the closing. In the case of JSX, it generated code that had a different meaning. Fortunately, since we don't usually commit commented out code it didn't affect production code, but it is not a good experience while coding.
// Before
const x = (
<div
attr1={1}>
// attr3={3}
{children}
</div>
);
// After
const x = (
<div
attr1={1}
// attr3={3}
>
{children}
</div>
);
In 1.0, we made class be inline inside of arrow functions. It turns out that it doesn't work great when the class is non trivial, so we are reverting this change. We're trying really hard to avoid making trashy decisions like this where the style changes back and forth, but we allow ourselves to do it sometimes to fix mistakes!
// Before
export default (ViewComponent: Function, ContainerComponent: Function) => class
extends React.Component {
static propTypes = {};
};
// After
export default (ViewComponent: Function, ContainerComponent: Function) =>
class extends React.Component {
static propTypes = {};
};
This one was found by fuzzing. You're unlikely going to hit this in real code but it's good to know it is fixed!
// Input
if (a) {
b;
;
}
// Before
if (a) {
b;
}
// After
if (a) {
b;
}
The new version differs by 48 commits0.
a81d5c1
1.3.0
0785726
Inline template literals as arrow body (#1485)
f59aeef
Break inline object first in function arguments (#1453) (#1173)
8f9bb3a
Break inline object first in function arguments (#1453)
54b8cac
Reorder flow object props (#1451)
c99a877
Do not break on [0] (#1441)
acfb14f
Don't break on empty arrays and objects (#1440)
bafd724
Don't break for unparenthesised single argument flow function (#1452)
a335c26
Add space around =
for flow generics default arguments (#1476)
4b7d265
Fix windows line ending on template literals (#1439)
e392093
Only add parenthesis on ternaries inside of arrow functions if doesn't break (#1450)
93cad97
Preserve inline comment as last argument (#1390)
314e963
Add parenthesis for unusual nested ternaries (#1386)
13f05fb
Proper indentation for template literals (#1385)
c521406
[RFC] Do not indent calls with a single template literal argument (#873)
There are 48 commits in total.
See the full diff
Update to this version instead π
This is the most requested feature for prettier. With 1.4.0, you can now use prettier to format your .ts
and .tsx
files!
The way prettier works is by using those project to generate an AST representation of the code and print it. Both babylon (the parser that powers babel) and flow are producing an AST approximately following the estree format for the JavaScript parts and then have special nodes for Flow-specific ones.
TypeScript, the same way as Flow, introduces special nodes for the syntax it introduces. Unfortunately, it doesn't follow the estree format for the rest of the JavaScript language. This puts us in a rough spot with prettier as we would have to essentially completely fork it in order to print TypeScript.
This incompatibility with the AST is not a new problem and another project struggled with it: ESLint. Because the AST is different, none of the ESLint rules are working. Fortunately for us, @JamesHenry and @soda0289 wrote a project called typescript-eslint-parser which takes a TypeScript AST and convert it to an estree one, just what we need for prettier!
After that project got setup inside of prettier, @azz, @despairblue and @Pajn implemented all the TypeScript-specific nodes and ensured that the 13k tests of the TypeScript test suite are correctly passing. This was a huge undertaking and it is finally ready to be used :)
We tested prettier on the biggest TypeScript projects we could find on GitHub to ensure that it prints correct code. We haven't spent a lot of time trying to optimize the way code is formatted yet, so if you see something strange, please raise an issue!
While TypeScript is the most requested feature from open source, CSS is the biggest one from Facebook engineers. Once you are used to pretty print your code in one language, you want to do it everywhere!
It turns out that CSS is a much smaller language than JavaScript and supporting it only took a few days. We are using postcss by @ai as the underlying parser which is able to parse CSS, Less and SCSS. We also depend on postcss-values-parser, postcss-selector-parser by @ben-eb postcss-media-query-parser by @dryoma.
Unfortunately, postcss right now doesn't parse Sass nor Stylus. We'd be happy to support them if someone is willing to do the work of printing them.
Note that prettier is currently just formatting the code, it does not respect any options yet such as singleQuote
nor is doing any color or number normalization like we do for JavaScript.
The first phase of the project was to make prettier output correct and good looking code. Now that it's in a good shape, we can spend time on making the integrations better. We just introduced support for two great features: maintain cursor position and being able to format a range instead of the entire file.
Note that we just landed the support inside of prettier itself, none of the editor integrations are using it yet. Also, we haven't really tried them out in practice so we're likely going to have to fix rough edges with them!
cursorOffset
option for cursor translation (#1637) by @josephfrazierRight now, we let editors figure out where the cursor should be, which they do an okay job at. But since we are printing the code, we can give the correct position!
--range-start/end
options to format only parts of the input (#1609) by @josephfrazierThis one is a very often requested feature. Right now prettier only formats the entire file. Now it is possible to format a range.
The way it works is by going up through the AST in order to find the closest statement. This way you don't need to select exactly the right range that is valid. You can just drag in the rough place where the code you want to reformat it, and it's going to!
Since we are now formatting CSS and TypeScript, it is not convenient to have to specify the parser for every file. You can now pass the filepath of the file you are working on and prettier will read the extension and figure out the right parser to use.
The biggest remaining issue that people have with prettier when printing JSX is when it is used when printing text. The behavior of prettier used to add an ugly {" "}
before and if a line was too long, just leave it alone. Now we treat each word as a token and are able to make it flow correctly.
This is an awesome piece of work by @karl as not only did he implement the feature, but also introduced a new primitive inside of prettier in order to print a sequence of elements and break as soon as one hits the edge.
// Before
<div>
Please state your
{" "}
<b>name</b>
{" "}
and
{" "}
<b>occupation</b>
{" "}
for the board of directors.
</div>
// After
<div>
Please state your <b>name</b> and <b>occupation</b> for the board of
directors.
</div>
People writing functional components are going to be happy about this one. We no longer put parens for arrow functions that return JSX.
// Before
const render1 = ({ styles }) => (
<div style={styles}>
Keep the wrapping parens. Put each key on its own line.
</div>
);
// After
const render1 = ({ styles }) =>
<div style={styles}>
Keep the wrapping parens. Put each key on its own line.
</div>;
Template literal printing has always caused prettier a lot of difficulties. With 1.3.0 we massively improved the situation and with this release, I believe that we handle all the common situations in a good way.
In order to workaround issues, we added an utility that removes empty lines from the output, but it yielded some really weird results sometimes, this is now gone. Another tweak we've done is instead of indenting when ${
starts, we indent where the line that contains ${
starts.
Let us know if you still have issues with how template literals output after this release!
// Before
const Bar = styled.div`
color: ${props => (props.highlight.length > 0 ? palette([
'text',
'dark',
'tertiary'
])(props) : palette([
'text',
'dark',
'primary'
])(props))} !important;
`
// After
const Bar = styled.div`
color: ${props =>
props.highlight.length > 0
? palette(["text", "dark", "tertiary"])(props)
: palette(["text", "dark", "primary"])(props)} !important;
`
We have a lot of fine-tuned logic for how to break things after assignment (eg a = ...
). We are now using the same one for object values. This should help for multi-line boolean logic, or big conditionals. This is also a good example of how we can create a consistent printer.
// Before
const o = {
somethingThatsAReallyLongPropName: this.props.cardType ===
AwesomizerCardEnum.SEEFIRST,
};
// After
const o = {
somethingThatsAReallyLongPropName:
this.props.cardType === AwesomizerCardEnum.SEEFIRST,
};
There's been a steady stream of people complaining about the way it was rendered and was put on the list of things that are probably hard to do, will check later. It turned out to be super easy, so here you go!
// Before
const anyTestFailures = !(aggregatedResults.numFailedTests === 0 &&
aggregatedResults.numRuntimeErrorTestSuites === 0);
// After
const anyTestFailures = !(
aggregatedResults.numFailedTests === 0 &&
aggregatedResults.numRuntimeErrorTestSuites === 0
);
We were already doing this for if statements, we should be consistent and also do it for loops.
// Before
for (a in b)
var c = {};
// After
for (a in b) var c = {};
We shouldn't indent things twice ;)
// Before
type Foo = Promise<
| { ok: true, bar: string, baz: SomeOtherLongType }
| { ok: false, bar: SomeOtherLongType }
>;
// After
type Foo = Promise<
{ ok: true, bar: string, baz: SomeOtherLongType } |
{ ok: false, bar: SomeOtherLongType }
>;
The detection code for whether an arrow function should be written without parenthesis just checked if there was a comment, but instead we only want comments that are inline like (/* comment */ num)
, not end of line comments.
// Before
KEYPAD_NUMBERS.map((num) => ( // Buttons 0-9
<div />
));
KEYPAD_NUMBERS.map(num => ( // Buttons 0-9
<div />
));
This avoids making it seems like it is indented by 4 characters instead of two. The downside is that if the condition is multi-line it's not going to be properly aligned, but I feel it's a better trade-offs. If you are doing nested ternaries, you usually have small conditions.
// Before
aaaaaaaaaaaaaaa
? bbbbbbbbbbbbbbbbbb
: ccccccccccccccc
? ddddddddddddddd
: eeeeeeeeeeeeeee ? fffffffffffffff : gggggggggggggggg;
// After
aaaaaaaaaaaaaaa
? bbbbbbbbbbbbbbbbbb
: ccccccccccccccc
? ddddddddddddddd
: eeeeeeeeeeeeeee ? fffffffffffffff : gggggggggggggggg;
We don't need to use the indentation to disambiguate another block as nothing can come after.
// Before
<div
src={
!isEnabled &&
diffUpdateMessageInput != null &&
this.state.isUpdateMessageEmpty
}
/>;
// After
<div
src={
!isEnabled &&
diffUpdateMessageInput != null &&
this.state.isUpdateMessageEmpty
}
/>;
We are already trying to cleanup strings in various ways, this is another small addition that's going to remove \
that are not needed.
// Before
a = 'hol\a';
// After
a = 'hola';
We want to inline objects inside of a boolean expression as it looks weird to have {
on its own line. But it turns out that it leads to weird behaviors for empty objects. So we keep them on their own line if they are empty.
const x = firstItemWithAVeryLongNameThatKeepsGoing ||
secondItemWithALongNameAsWell || {};
// After
const x =
firstItemWithAVeryLongNameThatKeepsGoing ||
secondItemWithALongNameAsWell ||
{};
It is common to assign multiple values inside of a for loop, now we don't add parenthesis anymore.
// Before
for ((i = 0), (len = arr.length); i < len; i++) {
// After
for (i = 0, len = arr.length; i < len; i++) {
If you put block comments inside of arrow functions, we no longer mess everything up!
// Before
export const bem = block => /**
* @param {String} [element] - the BEM Element within that block; if undefined, selects the block itself.
*/
element => /**
* @param {?String} [modifier] - the BEM Modifier for the Block or Element; if undefined, selects the Block or Element unmodified.
*/
modifier =>
// After
export const bem = block =>
/**
* @param {String} [element] - the BEM Element within that block; if undefined, selects the block itself.
*/
element =>
/**
* @param {?String} [modifier] - the BEM Modifier for the Block or Element; if undefined, selects the Block or Element unmodified.
*/
modifier =>
Another place where we have to do special logic for comments!
// Before
import {
ExecutionResult,
DocumentNode,
/* tslint:disable */
SelectionSetNode,
} /* tslint:enable */ from 'graphql';
// After
import {
DocumentNode,
/* tslint:disable */
SelectionSetNode,
/* tslint:enable */
} from 'graphql';
We handled some placements before and kept adding places where they could appear, now we switch to a more general approach. Hopefully those issues shouldn't crop up in the future anymore.
// Before
const configModel = this.baseConfigurationService.getCache().consolidated // global/default values (do NOT modify)
.merge(this.cachedWorkspaceConfig);
// After
const configModel = this.baseConfigurationService
.getCache()
.consolidated // global/default values (do NOT modify)
.merge(this.cachedWorkspaceConfig);
// Before
f(action => next =>
next(action));
// After
f(action => next =>
next(action),
);
This mostly affects Facebook engineers where we automatically add $FlowFixMe
when pushing a new version of flow. Now it no longer messes up those comments.
// Before
const aDiv = /* $FlowFixMe */
(
<div className="foo">
Foo bar
</div>
);
// After
const aDiv = (
/* $FlowFixMe */
<div className="foo">
Foo bar
</div>
);
This one has been very often requested. We used to only break multiple variable declarations if the line was > 80 columns. Now we do it regardless if there's at least one with an assignment.
// Before
var numberValue1 = 1, numberValue2 = 2;
// After
var numberValue1 = 1,
numberValue2 = 2;
The expanded version of flow union looks good when they are many objects but if it's used for nullability, the it looks very weird. We're now inlining | null
and | void
.
// Before
interface RelayProps {
articles:
| Array<
| {
__id: string,
}
| null
>
| null
}
// After
interface RelayProps {
articles: Array<{
__id: string,
} | null> | null,
}
We no longer break on extends
. This should make classes with extends that can break look less wonky.
// Before
class MyContractSelectionWidget
extends React.Component<
void,
MyContractSelectionWidgetPropsType,
void
> {
method() {}
}
// After
class MyContractSelectionWidget extends React.Component<
void,
MyContractSelectionWidgetPropsType,
void
> {
method() {}
}
The same way we don't break long require
calls, we no longer break import
statements if there is only a single thing being imported.
// Before
import somethingSuperLongsomethingSuperLong
from "somethingSuperLongsomethingSuperLongsomethingSuperLong";
// After
import somethingSuperLongsomethingSuperLong from "somethingSuperLongsomethingSuperLongsomethingSuperLong";
Did you know that if none of your code were statements, you could use ()
instead of {}
and ,
instead of ;
? Now you do. Some people exploit this fact when returning things from arrow functions. This is not recommended but it's easy to support in prettier so might as well Β―_(γ)_/Β―
// Before
const f = (argument1, argument2, argument3) =>
(doSomethingWithArgument(argument1), doSomethingWithArgument(
argument2
), argument1);
// After
const f = (argument1, argument2, argument3) => (
doSomethingWithArgument(argument1),
doSomethingWithArgument(argument2),
argument1
);
Loops with empty body no longer have their {}
split into two lines.
// Before
while (true) {
}
// After
while (true) {}
// Before
switch (true) {
case true:
// Good luck getting here
case false:
}
// After
switch (true) {
case true:
// Good luck getting here
case false:
}
We used to find where to put comments by traversing the AST using the definition from ast-types. This occasionally caused issues when some field wasn't declared, we wouldn't find the node and either print comments in an incorrect location or throw an error. It turns out that we don't need to keep this mapping and can just traverse the objects and if a node has a type
field, then it's a node.
// Before
Error: did not recognize object of type "ObjectTypeSpreadProperty"
// After
type X = {...Y/**/};
type X = {/**/...Y};
If you were adding invisible characters inside of JSX text, we would replace them by regular spaces. I don't know why anyone would ever want to do that, but now we print it back as is!
We used to have some pretty complicated (and not working well) code to handle comments inside of template literals. We introduced a really nice solution for JSX {}
expressions. The idea is to introduce a boundary before the end of the }
and if we still have unprinted comments, then flush them all at once, put a \n and print the }
. We are now using this logic for template literals :)
// Before
`${0} // comment`;
// After
`${
0
// comment
}`;
We don't have an automated way to put parenthesis, we instead specify all the possible combinations of nodes and when they should or shouldn't have parenthesis. So there's likely a long tail of unusual combinations that are still remaining. In this case, we made await
handling a lot more robust by both adding parenthesis where they are needed and removing them when they are not.
// Before
(await spellcheck) && spellcheck.setChecking(false);
new A((await x));
// After
await (spellcheck && spellcheck.setChecking(false));
new A(await x);
Another long tail option that we haven't got right!
// Before
type T = { method: () => void };
// After
type T = { get method(): void }
Another case of sneaky parenthesis that we didn't properly add!
// Before
type ExtractType = <A>B<C> => D
// After
type ExtractType = <A>(B<C>) => D
We want prettier to be able to parse all the JavaScript out there. For babylon parser, we have to chose whether a file is using strict mode or not. We opted in to use strict mode by default as most files parse that way. But if you have octal literals like 0775
, it would not even parse. Now if it fails to parse in strict mode, we're going to try again in non-strict. We also allow return
outside of a function as it's valid in node files.
// Before
SyntaxError
// After
return 0775;
--write
to be used with --list-different
(#1633)This is useful to combine the two if you are writing a commit hook to tell the user what actually changed in a single command.
It's very easy to run prettier over the node_modules/
folder by mistake which is something you almost never want to. So now we disable it by default and add a --with-node-modules
option if you really want to.
We enabled the option to go through .dotfiles in the glob parsing library we are using. This means that writing *
will now catch .eslintrc
.
Version 1.0.0 of prettier just got published.
The version 1.0.0 is not covered by your current version range.
Without accepting this pull request your project will work just like it did before. There might be a bunch of new features, fixes and perf improvements that the maintainers worked on for you though.
I recommend you look into these changes and try to get onto the latest version of prettier. Given that you have a decent test suite, a passing build is a strong indicator that you can take advantage of these changes by merging the proposed change into your project. Otherwise this branch is a great starting point for you to work on the update.
Commits
The new version differs by 123 commits .
23756cd
1.0
1a0067e
re-run tests
fe7ebc0
Fix edge cases triggered by newlines in arrow functions (#1217)
3709105
Remove now unused getFirstString (#1231)
4d9edec
Fix trailing comma for rest element in Babylon (#1230)
4dfe92a
Ensure JSXOpeningElement does not break with single text attr on Babylon (#1229)
485028c
Fix ALL_PASERS typo in run_spec (#1227)
27d827a
Remove hasContent (#1222)
33fdcae
Remove isCurlyBracket and isEmptyBlock (#1221)
f68531a
Fix overflow for last argument expansion (#1224)
5fa8df3
Add cli option for --no-semi (#1223)
4a4e181
Do not merge member chain if there's a comment in-between (#1218)
5d8ffd0
Fix own line last if comment (#1219)
ee7cfa9
Ignore empty statement in switch newline detection (#1220)
3a7559b
Preserve comment for last arg of ObjectMethod (#1216)
There are 123 commits in total. See the full diff.
Not sure how things should work exactly?
There is a collection of [frequently asked questions](https://greenkeeper.io/faq.html) and of course you may always [ask my humans](https://github.com/greenkeeperio/greenkeeper/issues/new).Your Greenkeeper Bot :palm_tree: