prettier / prettier Goto Github PK
View Code? Open in Web Editor NEWPrettier is an opinionated code formatter.
Home Page: https://prettier.io
License: MIT License
Prettier is an opinionated code formatter.
Home Page: https://prettier.io
License: MIT License
I get the following errors when using JSX like the following:
<InputGroup.Button><Button className="btn btn btn-primary" type="submit">Save</Button></InputGroup.Button>
I think its because of the "." in InputGroup.Button. If I take out that line then the file is able to be formatted.
prettier errors:
/usr/local/lib/node_modules/prettier/src/printer.js:1046
).join([ path.call(print, "object"), path.call(print, "property") ]);
^
TypeError: fromString(...).join is not a function
at genericPrintNoParens (/usr/local/lib/node_modules/prettier/src/printer.js:1046:7)
at genericPrint (/usr/local/lib/node_modules/prettier/src/printer.js:128:28)
at p (/usr/local/lib/node_modules/prettier/src/printer.js:77:37)
at exports.printComments (/usr/local/lib/node_modules/prettier/src/comments.js:276:17)
at printGenerically (/usr/local/lib/node_modules/prettier/src/printer.js:77:12)
at FastPath.call (/usr/local/lib/node_modules/prettier/src/fast-path.js:113:16)
at genericPrintNoParens (/usr/local/lib/node_modules/prettier/src/printer.js:1106:14)
at genericPrint (/usr/local/lib/node_modules/prettier/src/printer.js:128:28)
at p (/usr/local/lib/node_modules/prettier/src/printer.js:77:37)
at exports.printComments (/usr/local/lib/node_modules/prettier/src/comments.js:276:17)
Taking some inspiration from @vjeux. Here is rundown through the code base I am working on
=
Should jscodefmt sort JSX props? I heard refmt does something like that. I haven't tried it yet.
Rewrite expression using ternary operator
(
for anonymous generator functionsMy node scripts with an initial shebang line #!/usr/bin/env node
are getting converted to ///usr/bin/env node
. These lines should be output unchanged in the formatted code.
Since the first one went really well, let's do another round :)
The issues are getting more scoped and less serious :)
}
on their own line&&
is broken, would be nice to break all of them into their own line;
for export defaultI have observed that this made me document code more often.
I ran prettier on some old code which used the classic jQuery(function() …)
structure and was a little surprised by the results. Here's a reduction:
jQuery(function() {
'use strict';
return 1;
});
placed the use strict
declaration on the same line as the function (and added a trailing space after the semicolon):
jQuery(function() { "use strict";
return 1;
});
With similar constructs, this doesn't happen:
$ prettier <(echo -e "function foo () {\n\t'use strict';\n\treturn 1;\n}")
function foo() {
"use strict";
return 1;
}
$ prettier <(echo -e "var foo = function() {\n\t'use strict';\n\treturn 1;\n};")
var foo = function() {
"use strict";
return 1;
};
$ prettier <(echo -e "(function() {\n\t'use strict';\n\treturn 1;\n})();")
(function() {
"use strict";
return 1;
})();
I haven't looked to see what's triggering this but it's probably connected to the line-length logic since it'll wrap once you hit that threshold:
$ prettier <(echo -e "otherFunctionWithANameSoLongThatItWillExceedTheMaximumLineLength(function() {\n\t'use strict';\n\treturn 1;\n});")
otherFunctionWithANameSoLongThatItWillExceedTheMaximumLineLength(function() {
"use strict";
return 1;
});
This strikes me as a really ugly format:
$ echo "lots + of + additions + are + put + into + some + weird + format + thats + ugly > 0" > /tmp/test.js && prettier /tmp/test.js
lots + of + additions + are + put + into + some + weird + format + thats +
ugly >
0;
Better would be:
lots + of + additions + are + put + into + some + weird + format + thats +
ugly > 0;
Do you agree, or is this intentionally the format used by prettier?
Hope this is the appropriate place for tracking this.
For anyone interested in adding this, please see these potential references:
https://github.com/Chiel92/vim-autoformat/blob/master/plugin/autoformat.vim
I'm running Node 6.2.1 on Windows 10. When running npm test
on a fresh repo, I get the following error:
$ npm test
> [email protected] test C:\Users\weeseng\Documents\GitHub\prettier
> jest
TypeError: string.replace is not a function
at string (C:\Users\weeseng\Documents\GitHub\prettier\node_modules\jest-util\build\index.js:45:19)
at p (C:\Users\weeseng\Documents\GitHub\prettier\node_modules\jest\node_modules\jest-cli\build\SearchSource.js:65:26)
at new SearchSource (C:\Users\weeseng\Documents\GitHub\prettier\node_modules\jest\node_modules\jest-cli\build\SearchSource.js:101:34)
at Runtime.createHasteContext.then.hasteMap (C:\Users\weeseng\Documents\GitHub\prettier\node_modules\jest\node_modules\jest-cli\build\jest.js:191:20)
at process._tickCallback (internal/process/next_tick.js:103:7)
npm ERR! Test failed. See above for more details.
Not too familiar with Jest, so I can't really help debug :(
This is definitely an edge case but it might surprise people with placeholders, etc. if they aren't carefully reviewing changes:
function foo() {
//foobar
}
becomes:
function foo() {}
Adding any sort of real work to that code will cause the comment to be retained:
function foo() {
//foobar
1;
}
function foo() {
//foobar
1;
}
I always thought that indenting chained functions was problematic, since as far as the parser is concerned, there is no block until it encounters the .
.
That's why I prefer
fn()
.then(foo => bar())
.finally(cleanup)
indenting would mean this code style:
fn().
then(foo => bar()).
finally(cleanup)
...which is of course terrible because the .
is easy to miss at the end of the line and you need to manage it when moving lines around.
Hence: please make chaining indentation configurable.
I ran prettier against our large-ish codebase, and aside from several instances of #23, I got one error:
where prettier put a colon in front of the any
. Simply removing the colon makes it valid.
Expected:
function Component() {
return (
<div
id="longid"
className="longclassname"
foo="longvalue"
bar="longvalue"
baz="longvalue"
>
hello
</div>
);
}
Actual
function Component() {
return (
<div id="longid" className="longclassname" foo="longvalue" bar="longvalue" baz="longvalue">
hello
</div>
);
}
Running prettier --write --single-quote src/*.js
or when using with package.json
like this:
{
"scripts": {
"prettify": "prettier --write --single-quote",
"prettify:src": "npm run prettify -- src/*.js *.js",
}
}
it only processes the first file that the glob pattern is resolving. In my case running npm run prettify:src
producing the following command:
prettier --write --single-quote "src/getDataTransferItems.js" "src/getDataTransferItems.spec.js" "src/index.js" "src/index.spec.js" "testSetup.js" "wallaby.config.js" "webpack.config.js"
But only src/getDataTransferItems.js
got processed.
For
<span>
foo <span>bar</span>
</span>
I got
<span>
foo<span>bar</span>
</span>;
which would render foo bar
vs foobar
.
Thanks for the great tool, though! Hope to adopt it once it becomes stable 🌞
Does prettier have any sublime text plugin? The README only mentions Atom and emacs.
Would be great to have a plugin for Visual Studio Code as well. I may give it a shot if I get some free time but I'd be just as happy if someone beat me to it. :)
Comments in this style
{/* Some comment */}
<div />
are replaced with
{}
<div />
I'm assuming its a bug?
That might be a personal preference, but I try to never use goto fail-style if
s.
This is OK:
if (err) return err;
This is not (but that's how prettier currently wraps):
if (err)
return err;
so I'd prefer if wrapping added curly braces like this:
if (err) {
return err;
}
export default MyComponent;
export default MyComponent
prettier is printing cases at the same indentation level as their parent switch statement. I indent cases inside a switch statement.
Now:
switch (something) {
case "foo":
// ...
break;
case "bar":
// ...
break;
}
Ideally:
switch (something) {
case "foo":
// ...
break;
case "bar":
// ...
break;
}
Example:
cat test.js | prettier
Block-scoped declarations (let, const, function, class) not yet supported outside strict mode
~/Code/main:master$ prettier
/Users/scole/.nodenv/versions/4.6.1/lib/node_modules/prettier/bin/prettier:32
let input;
^^^
SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:373:25)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Function.Module.runMain (module.js:441:10)
at startup (node.js:139:18)
at node.js:974:3
zsh: exit 1 prettier
$ node --version
v4.6.1
I had a bit of code where a trailing comment was moved to the next line when there's another statement after the function. This can cause confusion since it requires you to read the comment to know whether it applies to the line before or after and it looks like it would actually cause things like // eslint-disable-line
to apply to a different statement.
function foobar() {
var foo = bar;
var bar = fooBarBaaz(); // foo all the bars
var baaz = 'quux';
}
becomes:
function foobar() {
var foo = bar;
var bar = fooBarBaaz();
// foo all the bars
var baaz = "quux";
}
This does not happen if the comment is on the last line of a function.
prettier is changing my new A
s into new A()
. I would prefer it not do that.
I think it would be valuable to support for some type of file that contains prettier's config so that projects can check it in source control.
I can see 2 cases where this would be useful.
Could be it's own file (something like .editorconfig
) or maybe part of package.json
.
In files using ES2015 Loader spec (e.g. bundle splitting with [email protected]), import(...)
throws with SyntaxError: Unexpected token
.
This is true whether using the flow parser or babylon
Sample code:
import React from 'react'
import idbKeyval from 'idb-keyval'
import Shell from './components/app-shell'
class AppShell extends React.Component {
constructor () {
super()
this.state = {app: <Shell />}
}
componentWillMount () {
Promise.all([
idbKeyval.get('store'),
import('./root')
])
.then(
([data, module]) => { this.setState({app: <module.default initialData={data} /> })},
(err) => {console.log(err)}
)
.catch((err) => {
console.log('Chunk loading failed', err)
})
}
render () {
return this.state.app
}
}
export default AppShell
I often use parens with JSX ternaries to align opening and closing blocks, so that each "if" or "child" indentation is just one more indentation level deep:
prettier, like many AST-based JSX formatters, strips the parens and moves the opening tag of each JSX element up to where the paren was, which looks weird:
This is an amazing tool, any chance at supporting TypeScript as well?
before
function thing(arg) {
return arg;
}
export default thing;
after
function thing(arg) {
return arg;
}
export default thing // <-- missing semi colon
E.g. semicolons: true
to use semicolons at the end of statements (default), and semicolons: false
to not use semicolons.
You’re going to be under a lot of pressure to make X, Y, and Z, configurable.
Configuration is a perfect example of tragedy of the commons.
Everybody wants to add just a tiny piece of configuration to satisfy their use case. As a result we end up with inconsistently designed tools, with unexpected combinations that don’t work correctly, with bugs and regressions that, when fixed in one configuration, break something else with another configuration.
The requests for configuration are vocal. The requests to stay simple are often silent.
I just wanted to take a moment to say there are some of us who actually appreciate tools with limited scope that don’t attempt to solve everybody’s use case, and instead do a specific thing well.
e.g.
<BaseForm url="/auth/google" method="GET" colour="blue" size="large" submitLabel="Sign in with Google" />
should probably be converted into
<BaseForm
url="/auth/google"
method="GET"
colour="blue"
size="large"
submitLabel="Sign in with Google"
/>
foo(bar => {
return qux;
})
Is formatted as above (which seems fine), however I would expect
foo(bar => baz => {
return qux;
})
rather than
foo(
bar => baz => {
return qux;
}
);
A similar example with a const instead of a function call formats as
const foo = bar => baz => {
return qux;
};
So, I have no idea why the function call is getting extra newlines.
(Granted, it would be even nicer if the unnecessary curlies and return
were removed, but I'm guessing that is beyond the scope of this tool.)
Not sure if this is a bug or just a rare enough case that it doesn't matter
Input
something()
.something
.something()
.something
.something()
.something
.something()
Output
something().something.something().something.something().something.something();
(Longer than 60 chars)
Input
someVeryLongMethodObjectName
.withSomeVeryLongObjectKey
.andAnotherLongKey;
Output
someVeryLongMethodObjectName.withSomeVeryLongObjectKey.andAnotherLongKey;
My node --version
:
v4.4.7
My npm --version
:
3.10.5
When I run:
npm i prettier
./node_modules/.bin/prettier
I get the following error:
node_modules/prettier/bin/prettier:33
let input;
^^^
SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:373:25)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Function.Module.runMain (module.js:441:10)
at startup (node.js:139:18)
at node.js:968:3
I wonder if I missed something or if the package should be compiled with Babel to es5.
The bracket notation used here to avoid issues in older browsers that don't handle reserved words well is being changed to incorrect syntax
["catch"]
becomes ."catch"
causing Uncaught SyntaxError: Unexpected string
This would probably be a controversial decision but template literal strings are just better. No escaping, easy interpolation, multiline when needed, etc.
This article by @bevacqua introduced me to the idea https://ponyfoo.com/articles/template-literals-strictly-better-strings and I've been using straight template literal strings in Gatsby for the past month or so with great success. Can't imagine going back to the morass of single vs. double quotes now.
This would allow configuration of line breaks and tab characters, at least: http://editorconfig.org
Currently any object which isn't really long is written inline. However I usually prefer if an object has been written "vertically" that the nested objects would be written "vertically" too. What's your opinion on this?
Here's an example of what I mean, personally I think the previous version makes more sense, but I'd love to be enlightened
const options = {
find: '',
placeholder: undefined,
mark: false,
- class: {
- visible: undefined,
- hidden: 'hidden'
- },
+ class: { visible: undefined, hidden: 'hidden' },
dynamic: false,
minCharacters: 0,
hiddenAttr: false
}
There are some minor issues with the printing of flow union types. I'll try to break down the cases:
Input
type T = A | B;
This works as expected 👍
Input
type Test = '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' | '10';
type Test = 'a-long-string' | 'another-long-string' | 'yet-another-long-string';
type Test = { eventName: 'Foo', a: number } | { eventName: 'Bar', b: string } | { eventName: 'Baz', c: Object };
Output
type Test = "1" |
"2" |
"3" |
"4" |
"5" |
"6" |
"7" |
"8" |
"9" |
"10";
type Test = "a-long-string" |
"another-long-string" |
"yet-another-long-string";
type Test = { eventName: "Foo", a: number } |
{ eventName: "Bar", b: string } |
{ eventName: "Baz", c: Object };
Expected Output
type Test =
"1" |
"2" |
"3" |
"4" |
"5" |
"6" |
"7" |
"8" |
"9" |
"10";
type Test =
"a-long-string" |
"another-long-string" |
"yet-another-long-string";
type Test =
{ eventName: "Foo", a: number } |
{ eventName: "Bar", b: string } |
{ eventName: "Baz", c: Object };
Input
export type Comment = {
type: 'CommentLine';
_CommentLine: void;
value: string;
end: number;
loc: {
end: {column: number, line: number},
start: {column: number, line: number},
};
start: number;
} | {
type: 'CommentBlock';
_CommentBlock: void;
value: string;
end: number;
loc: {
end: {column: number, line: number},
start: {column: number, line: number},
};
start: number;
};
Output
export type Comment = {
type: "CommentLine",
_CommentLine: void,
value: string,
end: number,
loc: {
end: { column: number, line: number },
start: { column: number, line: number }
},
start: number
} |
{
type: "CommentBlock",
_CommentBlock: void,
value: string,
end: number,
loc: {
end: { column: number, line: number },
start: { column: number, line: number }
},
start: number
};
Expected Output
Same as input, or something consistent with the previous example.
Would love this!
import React, { Component } from 'react';
Gets replaced with
import React, {Component} from "react";
I havent seen that convention before. For reference,
const thing = {React};
Transforms into
const thing = { React };
In Prettier's live demo there's this:
<div>
hello ${name}! JSX is <strong>supported</strong>
</div>
And it's formatted as:
<div>
hello ${name}! JSX is<strong>supported</strong>
</div>
We can see that spaces around tags [and regular JS expressions] in the same line are missing.
You can also reproduce the issue this way:
<div>
text {name} more text and <em>tag</em> and text
</div>
Formatted as:
<div>
text{name}more text and<em>tag</em>and text
</div>
This looks awesome already. I ran the formatter through the nuclide codebase ( https://github.com/facebook/nuclide/tree/master/pkg ) and here are the things I'd love to get tweaked so that we can use it at Facebook :)
When the last argument of a function call is a function, object or array, and all the previous arguments fit in one line, want to inline it.
call(a, b, () => {
});
{}
and []
,
for type object separator instead of ;
?
and :
I don't think it's possible to automatically add empty lines in the right place most of the time. I think this should be under the developer control to decide where to put them.
&
and |
Something
.call(
...
)
.something.call( ... )
.call( ... );
The way I want it to look is that if it doesn't fit into a single line, every .call() is on its own line and indented two spaces. The way to do it is to look for CallExpression and traverse all the CallExpressions and MemberExpressions and rewrite them in this way.
I've found a strange case when using Arrow functions, chaining methods off an object inside the arrow function.
If I shorten the length of the variable name
or shorten the first method name
then it collapses and displays more correctly.
I also noticed that changing the name of the otherLongfunctionName
doesn't have any effect. In either case above, both long names push the line length beyond the acceptable length. This causes the arrow function parameters to be put on a new line, even though line-breaking after this
would lead to a better result. IMO the "problem" examples I provided are already formatted ideally.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.