Prettier 1.19: Lang erwartete Vue-Option, TypeScript 3.7 und neue JavaScript-Features
Diese Seite wurde von PageTurner AI übersetzt (Beta). Nicht offiziell vom Projekt unterstützt. Fehler gefunden? Problem melden →
Dieses Release fügt die lang erwartete Option --vue-indent-script-and-style, Unterstützung für TypeScript 3.7 und einige hochmoderne JavaScript-Syntax hinzu. Ganz zu schweigen von einer ganzen Reihe von Fehlerbehebungen und Verbesserungen!
Höhepunkte
Vue
Hinzufügen von --vue-indent-script-and-style (#6157 von @kamilic)
Die neue Option --vue-indent-script-and-style steuert, ob der Code innerhalb von <script>- und <style>-Tags in Vue-Dateien eingerückt werden soll. Einige Nutzer (wie der Schöpfer von Vue) verzichten auf Einrückung, um eine Einzugsebene zu sparen, was jedoch Code-Folding in Editoren beeinträchtigen kann. Damit schließen wir unser meistkommentiertes Issue und verbessern die Arbeitserfahrung vieler Vue-Entwickler!
TypeScript
Unterstützung für TypeScript 3.7 (#6657 von @cryrivers)
Prettier 1.19 unterstützt die Syntax-Neuerungen des kommenden TypeScript 3.7:
(Hinweis: Ein Dependency-Upgrade für TypeScript 3.7 führt zum Wegfall der Node.js 6-Unterstützung bei GitHub-Direktinstallation. Über npm installiertes Prettier bleibt mit Node.js 4 kompatibel.)
Optional Chaining
// Input
const longChain = obj?.a?.b?.c?.d?.e?.f?.g;
const longChainCallExpression = obj.a?.(a,b,c).b?.(a,b,c).c?.(a,b,c).d?.(a,b,c).e?.(a,b,c).f?.(a,b,c)
// Prettier 1.19
const longChain = obj?.a?.b?.c?.d?.e?.f?.g;
const longChainCallExpression = obj
.a?.(a, b, c)
.b?.(a, b, c)
.c?.(a, b, c)
.d?.(a, b, c)
.e?.(a, b, c)
.f?.(a, b, c);
Nullish Coalescing
// Input
const cond = null;
const result = cond??'a';
const longChain = cond??cond??cond??'b';
// Prettier 1.19
const cond = null;
const result = cond ?? "a";
const longChain = cond ?? cond ?? cond ?? "b";
Assertion-Funktionen
// Input
function assertsString(x: any): asserts x {console.assert(typeof x === 'string');}
function assertsStringWithGuard(x: any): asserts x is string {console.assert(typeof x === 'string');}
// Prettier 1.19
function assertsString(x: any): asserts x {
console.assert(typeof x === "string");
}
function assertsStringWithGuard(x: any): asserts x is string {
console.assert(typeof x === "string");
}
declare-Modifikator für Klassenfelder
// Input
class B {p: number;}
class C extends B {declare p: 256 | 1000;}
// Prettier 1.19
class B {
p: number;
}
class C extends B {
declare p: 256 | 1000;
}
JavaScript
Unterstützung für Partial-Application-Syntax (#6397 von @JounQin)
// Input
const addOne = add(1, ?); // apply from the left
addOne(2); // 3
const addTen = add(?, 10); // apply from the right
addTen(2); // 12
// with pipeline
let newScore = player.score
|> add(7, ?)
|> clamp(0, 100, ?); // shallow stack, the pipe to `clamp` is the same frame as the pipe to `add`.
// Prettier 1.18
SyntaxError: Unexpected token (1:23)
> 1 | const addOne = add(1, ?); // apply from the left
| ^
2 | addOne(2); // 3
3 |
4 | const addTen = add(?, 10); // apply from the right
// Prettier 1.19
const addOne = add(1, ?); // apply from the left
addOne(2); // 3
const addTen = add(?, 10); // apply from the right
addTen(2); // 12
// with pipeline
let newScore = player.score |> add(7, ?) |> clamp(0, 100, ?); // shallow stack, the pipe to \`clamp\` is the same frame as the pipe to \`add\`.
Erkennung von Funktionskomposition durch Funktionsliterale in Argumenten (#6033 von @brainkim)
Bisher nutzten wir hartkodierte Namen aus dem funktionalen Programmieren (compose, flow, pipe, etc.), um Funktionskomposition zu erkennen. Dadurch wurden Aufrufe wie pipe stets mehrzeilig formatiert – selbst bei ausreichender Zeilenlänge:
source$
.pipe(
filter(x => x % 2 === 0),
map(x => x + x),
scan((acc, x) => acc + x, 0),
)
.subscribe(x => console.log(x));
Diese Heuristik führte jedoch zu falsch-positiven Fällen: Aufrufe passender Funktionen wurden unnötig umgebrochen, selbst ohne Funktionsargumente (#5769, #5969). Für viele war dieser pauschale Zeilenumbruch überraschend und suboptimal.
Unsere neue Heuristik erkennt Komposition am Vorhandensein von Funktionsliteralen. Sie bewahrt das gewünschte Umbruchverhalten, eliminiert aber die meisten falsch-positiven Fälle der alten Methode.
Testen Sie die Neuerung und geben Sie uns gerne Feedback!
// Input
eventStore.update(id, _.flow(updater, incrementVersion));
// Prettier 1.18
eventStore.update(
id,
_.flow(
updater,
incrementVersion
)
);
// Prettier 1.19
eventStore.update(id, _.flow(updater, incrementVersion));
Formatierung trotz Parser-Fehlern in bestimmten Fällen (#6816 von @thorn0 und dem Babel-Team)
Wir haben den Babel-Parser auf die neueste Version aktualisiert und dadurch kostenlos eine großartige Funktion erhalten. Prettier kann jetzt deinen Code formatieren, selbst wenn er in manchen Fällen ungültig ist, was deine Programmiererfahrung reibungsloser machen sollte. Dies wird sich mit der Zeit weiter verbessern, während Babel seinen Fehlerwiederherstellungs-Parsing-Modus optimiert. Lies mehr im Babel 7.7.0 Blogbeitrag!
// Input
let a = {
__proto__ : x,
__proto__ : y
}
let a = 2
// Prettier 1.18
SyntaxError: Redefinition of __proto__ property (3:3)
1 | let a = {
2 | __proto__ : x,
> 3 | __proto__ : y
| ^
4 | }
5 | let a = 2
// Prettier 1.19
let a = {
__proto__: x,
__proto__: y
};
let a = 2;
Weitere Änderungen
TypeScript
Korrektur optionaler berechneter Klassenfelder und -methoden (#6657 von @cryrivers, #6673 von @thorn0)
Dies ist weiterhin fehlerhaft, wenn der Schlüssel ein komplexer Ausdruck ist, wurde aber in folgenden Fällen behoben:
// Input
class Foo {
[bar]?: number;
protected [s]?() {}
}
// Prettier 1.18
class Foo {
[bar]: number;
protected [s?]() {};
}
// Prettier 1.19
class Foo {
[bar]?: number;
protected [s]?() {}
}
Kommentare nach JSX-Elementnamen mit Typargumenten gingen verloren (#6209 von @duailibe)
// Input
const comp = (
<Foo<number>
// This comment goes missing
value={4}
>
Test
</Foo>
);
// Prettier 1.18
const comp = <Foo<number> value={4}>Test</Foo>;
// Prettier 1.19
const comp = (
<Foo<number>
// This comment goes missing
value={4}
>
Test
</Foo>
);
Abstürze bei Verwendung von // in JSX-Texten behoben (#6289 von @duailibe)
Diese Version aktualisiert den TypeScript-Parser, um JSX-Texte mit Doppelslash (//) korrekt zu verarbeiten. In früheren Versionen führte dies zu Abstürzen von Prettier.
Korrekte Formatierung langer einzeiliger Mapped Types in einem Durchgang (#6420 von @sosukesuzuki)
Früher fügte Prettier bei der Formatierung langer einzeiliger Mapped Types zwar einen Zeilenumbruch ein, fügte aber erst beim zweiten Durchlauf ein Semikolon hinzu – was die Idempotenzregel von Prettier verletzte. Jetzt fügt Prettier das Semikolon bereits im ersten Durchlauf hinzu.
// Input
type FooBar<T> = { [P in keyof T]: T[P] extends Something ? Something<T[P]> : T[P] }
// Prettier 1.18
type FooBar<T> = {
[P in keyof T]: T[P] extends Something ? Something<T[P]> : T[P]
};
// Prettier 1.19
type FooBar<T> = {
[P in keyof T]: T[P] extends Something ? Something<T[P]> : T[P];
};
Typ-Parameter in Typ-Annotationen von Variablendeklarationen inline belassen (#6467 von @sosukesuzuki)
// Input
const fooooooooooooooo: SomeThing<boolean> = looooooooooooooooooooooooooooooongNameFunc();
// Prettier 1.18
const fooooooooooooooo: SomeThing<
boolean
> = looooooooooooooooooooooooooooooongNameFunc();
// Prettier 1.19
const fooooooooooooooo: SomeThing<boolean> = looooooooooooooooooooooooooooooongNameFunc();
Doppelte Klammern um Typen wurden manchmal fälschlich entfernt (#6604 von @sosukesuzuki)
// Input
type A = 0 extends ((1 extends 2 ? 3 : 4)) ? 5 : 6;
type B = ((0 extends 1 ? 2 : 3)) extends 4 ? 5 : 6;
type C = ((number | string))["toString"];
type D = ((keyof T1))["foo"];
// Prettier 1.18
type A = 0 extends 1 extends 2 ? 3 : 4 ? 5 : 6;
type B = 0 extends 1 ? 2 : 3 extends 4 ? 5 : 6;
type C = number | string["toString"];
type D = keyof T1["foo"];
// Prettier 1.19
type A = 0 extends (1 extends 2 ? 3 : 4) ? 5 : 6;
type B = (0 extends 1 ? 2 : 3) extends 4 ? 5 : 6;
type C = (number | string)["toString"];
type D = (keyof T1)["foo"];
Klammern um JSX beibehalten, wenn nötig, um Syntaxfehler zu vermeiden (#6640 von @sosukesuzuki)
// Input
(<a />).toString();
// Prettier 1.18
<a />.toString():
// Prettier 1.19
(<a />).toString();
Semikolon für Klassen-Eigenschaften vor Index-Signaturen beibehalten, wenn no-semi aktiviert ist (#6728 von @sosukesuzuki)
Ein erneutes Formatieren der Prettier-Ausgabe führte früher zu einem Syntaxfehler.
// Input
export class User {
id: number = 2;
[key: string]: any
}
// Prettier 1.18
export class User {
id: number = 2
[key: string]: any
}
// Prettier 1.19
export class User {
id: number = 2;
[key: string]: any
}
Verbesserte Argument-Entfaltung bei as-Typausdrücken (#6471 von @mattleff)
Früher brach Prettier bei Aufrufausdrücken mit as-Typausdrücken oder Typassertionen die Zeile unnötig um. Jetzt nutzt Prettier den durch den as-Typ oder die Typassertion enthaltenen Ausdruck, um über Zeilenumbrüche zu entscheiden.
// Input
const bar = [1,2,3].reduce((carry, value) => {
return [...carry, value];
}, ([] as unknown) as number[]);
// Prettier 1.18
const bar = [1, 2, 3].reduce(
(carry, value) => {
return [...carry, value];
},
([] as unknown) as number[]
);
// Prettier 1.19
const bar = [1,2,3].reduce((carry, value) => {
return [...carry, value];
}, ([] as unknown) as number[]);
TypeScript/Flow
Indentierung von Union-Typen in Tupeln korrigiert (#6381 von @squidfunk, #6605 von @thorn0)
// Input
type A = [
| AAAAAAAAAAAAAAAAAAAAAA
| BBBBBBBBBBBBBBBBBBBBBB
| CCCCCCCCCCCCCCCCCCCCCC
| DDDDDDDDDDDDDDDDDDDDDD
]
type B = [
| AAAAAAAAAAAAAAAAAAAAAA
| BBBBBBBBBBBBBBBBBBBBBB
| CCCCCCCCCCCCCCCCCCCCCC
| DDDDDDDDDDDDDDDDDDDDDD,
| AAAAAAAAAAAAAAAAAAAAAA
| BBBBBBBBBBBBBBBBBBBBBB
| CCCCCCCCCCCCCCCCCCCCCC
| DDDDDDDDDDDDDDDDDDDDDD
]
type C = [
| [AAAAAAAAAAAAAAAAAAAAAA | BBBBBBBBBBBBBBBBBBBBBB | CCCCCCCCCCCCCCCCCCCCCC | DDDDDDDDDDDDDDDDDDDDDD]
| [AAAAAAAAAAAAAAAAAAAAAA | BBBBBBBBBBBBBBBBBBBBBB | CCCCCCCCCCCCCCCCCCCCCC | DDDDDDDDDDDDDDDDDDDDDD]
]
// Prettier 1.18
type A = [
| AAAAAAAAAAAAAAAAAAAAAA
| BBBBBBBBBBBBBBBBBBBBBB
| CCCCCCCCCCCCCCCCCCCCCC
| DDDDDDDDDDDDDDDDDDDDDD
];
type B = [
| AAAAAAAAAAAAAAAAAAAAAA
| BBBBBBBBBBBBBBBBBBBBBB
| CCCCCCCCCCCCCCCCCCCCCC
| DDDDDDDDDDDDDDDDDDDDDD,
| AAAAAAAAAAAAAAAAAAAAAA
| BBBBBBBBBBBBBBBBBBBBBB
| CCCCCCCCCCCCCCCCCCCCCC
| DDDDDDDDDDDDDDDDDDDDDD
];
type C = [
| [
| AAAAAAAAAAAAAAAAAAAAAA
| BBBBBBBBBBBBBBBBBBBBBB
| CCCCCCCCCCCCCCCCCCCCCC
| DDDDDDDDDDDDDDDDDDDDDD
]
| [
| AAAAAAAAAAAAAAAAAAAAAA
| BBBBBBBBBBBBBBBBBBBBBB
| CCCCCCCCCCCCCCCCCCCCCC
| DDDDDDDDDDDDDDDDDDDDDD
]
];
// Prettier 1.19
type A = [
| AAAAAAAAAAAAAAAAAAAAAA
| BBBBBBBBBBBBBBBBBBBBBB
| CCCCCCCCCCCCCCCCCCCCCC
| DDDDDDDDDDDDDDDDDDDDDD
];
type B = [
(
| AAAAAAAAAAAAAAAAAAAAAA
| BBBBBBBBBBBBBBBBBBBBBB
| CCCCCCCCCCCCCCCCCCCCCC
| DDDDDDDDDDDDDDDDDDDDDD
),
(
| AAAAAAAAAAAAAAAAAAAAAA
| BBBBBBBBBBBBBBBBBBBBBB
| CCCCCCCCCCCCCCCCCCCCCC
| DDDDDDDDDDDDDDDDDDDDDD
)
];
type C = [
| [
| AAAAAAAAAAAAAAAAAAAAAA
| BBBBBBBBBBBBBBBBBBBBBB
| CCCCCCCCCCCCCCCCCCCCCC
| DDDDDDDDDDDDDDDDDDDDDD
]
| [
| AAAAAAAAAAAAAAAAAAAAAA
| BBBBBBBBBBBBBBBBBBBBBB
| CCCCCCCCCCCCCCCCCCCCCC
| DDDDDDDDDDDDDDDDDDDDDD
]
];
Kommentar-Verschiebung in Funktionsaufrufen wie useEffect behoben (#6270 von @sosukesuzuki)
Dies behebt einen Fehler bei Funktionsaufrufen mit einem Pfeilfunktion als erstem Argument und einem Array-Ausdruck als zweitem Argument (z.B. Reacts useEffect).
Wenn ein Kommentar vor dem zweiten Argument stand, versetzte Prettier ihn fälschlich in die darüberliegende Zeile und zerstörte die Einrückung.
Der Fehler trat nur bei Verwendung der Flow- und TypeScript-Parser auf.
// Input
useEffect(
() => {
console.log("some code", props.foo);
},
// eslint-disable-line react-hooks/exhaustive-deps
[]
);
// Prettier 1.18
useEffect(() => {
console.log("some code", props.foo);
}, // eslint-disable-line react-hooks/exhaustive-deps
[]);
// Prettier 1.19
useEffect(
() => {
console.log("some code", props.foo);
},
// eslint-disable-line react-hooks/exhaustive-deps
[]
);
Schließende Klammer nach Union-Typen in neue Zeile setzen (#6307 von @sosukesuzuki)
// Input
const foo = [abc, def, ghi, jkl, mno, pqr, stu, vwx, yz] as (
| string
| undefined
)[];
// Prettier 1.18
const foo = [abc, def, ghi, jkl, mno, pqr, stu, vwx, yz] as (
| string
| undefined)[];
// Prettier 1.19
const foo = [abc, def, ghi, jkl, mno, pqr, stu, vwx, yz] as (
| string
| undefined
)[];
Flow
Unterstützung für Enums hinzugefügt (#6833 von @gkz)
// Input
enum E of string {
A = "a",
B = "b",
}
// Prettier 1.19
enum E of string {
A = "a",
B = "b",
}
Klammern um Rückgabetypen von Pfeilfunktionen bei FunctionTypeAnnotation in ObjectTypeAnnotation (#6717 von @sosukesuzuki)
Dies ist eine Problemumgehung für einen Fehler im Flow-Parser. Ohne die Klammern würde der Parser einen Fehler werfen.
// Input
const example1 = (): { p: (string => string) } => (0: any);
// Prettier 1.18
const example1 = (): { p: string => string } => (0: any);
// Prettier 1.19
const example1 = (): ({ p: string => string }) => (0: any);
JavaScript
Arrays von Arrays/Objekten umbrechen, wenn jedes Element mehr als ein Element/Eigenschaft hat (#6694 von @sosukesuzuki)
Dadurch werden new Map-Aufrufe und Jest test.each-Aufrufe besser formatiert.
// Input
test.each([
{ a: "1", b: 1 },
{ a: "2", b: 2 },
{ a: "3", b: 3 }
])("test", ({ a, b }) => {
expect(Number(a)).toBe(b);
});
[[0, 1, 2], [0, 1, 2]];
new Map([
[A, B],
[C, D],
[E, F],
[G, H],
[I, J],
[K, L],
[M, N]
]);
// Prettier 1.18
test.each([{ a: "1", b: 1 }, { a: "2", b: 2 }, { a: "3", b: 3 }])(
"test",
({ a, b }) => {
expect(Number(a)).toBe(b);
}
);
[[0, 1, 2], [0, 1, 2]]
new Map([[A, B], [C, D], [E, F], [G, H], [I, J], [K, L], [M, N]]);
// Prettier 1.19
test.each([
{ a: "1", b: 1 },
{ a: "2", b: 2 },
{ a: "3", b: 3 }
])("test", ({ a, b }) => {
expect(Number(a)).toBe(b);
});
[
[0, 1, 2],
[0, 1, 2]
];
new Map([
[A, B],
[C, D],
[E, F],
[G, H],
[I, J],
[K, L],
[M, N]
]);
??-Präzedenz auf Stage-3-Proposal aktualisieren (#6404 von @vjeux, #6863 von @jridgewell)
Wir haben die Unterstützung für den Nullish-Coalescing-Operator an ein Spez-Update angepasst, das ihn nicht mehr unmittelbar in oder neben &&/||-Operationen erlaubt.
// Input
(foo ?? bar) || baz;
(foo || bar) ?? baz;
// Prettier 1.18
foo ?? bar || baz;
foo || bar ?? baz;
// Prettier 1.19
(foo ?? bar) || baz;
(foo || bar) ?? baz;
Hinweis: Da unsere Parser aktualisiert wurden, führt Code ohne Klammern nun zu einem Parse-Fehler.
Klammern für logische Ausdrücke mit gleichen Operatoren nicht mehr erforderlich (#6864 von @jridgewell)
// Input
foo && (bar && baz);
foo || (bar || baz);
foo ?? (bar ?? baz);
// Prettier 1.18
foo && (bar && baz);
foo || (bar || baz);
foo ?? (bar ?? baz);
// Prettier 1.19
foo && bar && baz;
foo || bar || baz;
foo ?? bar ?? baz;
Bessere Lesbarkeit von Klammern bei new-Aufrufen (#6412 von @bakkot)
// Input
var a = new (x().y)();
var a = new (x().y.z)();
var a = new (x().y().z)();
// Prettier 1.18
var a = new (x()).y();
var a = new (x()).y.z();
var a = new (x().y()).z();
// Prettier 1.19
var a = new (x().y)();
var a = new (x().y.z)();
var a = new (x().y().z)();
Kommentare in unären Ausdrücken mit Klammern erhalten (#6217 von @sosukesuzuki)
// Input
!(
/* foo */
foo
);
!(
foo // foo
);
// Prettier 1.18
!/* foo */
foo;
!foo; // foo
// Prettier 1.19
!(/* foo */ foo);
!(
foo // foo
);
Kommentare in getaggten Template-Literals nicht mehr verschieben (#6236 von @sosukesuzuki)
// Input
foo //comment
`
`;
// Prettier 1.18
foo` // comment
`;
// Prettier 1.19
foo // comment
`
`;
Leerzeilen in destrukturierten Pfeilfunktionsparametern konnten Einrückung und Idempotenz brechen (#6301 & #6382 von @sosukesuzuki)
Zuvor rückte Prettier Code seltsam ein, wenn eine Pfeilfunktion mit Objektdestrukturierung als Argument übergeben wurde. Details unter #6294.
// Input
foo(
({
a,
b
}) => {}
);
// Prettier 1.18
foo(({ a,
b }) => {});
// Prettier 1.19
foo(
({
a,
b
}) => {}
);
Formatierung von Objektdestrukturierung mit Parameter-Decorators korrigiert (#6411 von @sosukesuzuki)
// Input
class Class {
method(
@decorator
{ foo }
) {}
}
// Prettier 1.18
class Class {
method(@decorator
{
foo
}) {}
}
// Prettier 1.19
class Class {
method(
@decorator
{ foo }
) {}
}
Umgang mit leeren Objektmustern mit Typannotationen in Funktionsparametern (#6438 von @bakkot)
// Input
const f = ({}: MyVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongType) => {};
function g({}: Foo) {}
// Prettier 1.18
const f = ({
,
}: MyVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongType) => {};
function g({ }: Foo) {}
// Prettier 1.19
const f = ({}: MyVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongType) => {};
function g({}: Foo) {}
Schließende Klammer nach binären Ausdrücken in Funktionsaufrufen in neue Zeile setzen (#6441 von @sosukesuzuki)
// Input
(
aaaaaaaaaaaaaaaaaaaaaaaaa &&
bbbbbbbbbbbbbbbbbbbbbbbbb &&
ccccccccccccccccccccccccc &&
ddddddddddddddddddddddddd &&
eeeeeeeeeeeeeeeeeeeeeeeee
)();
// Prettier 1.18
(aaaaaaaaaaaaaaaaaaaaaaaaa &&
bbbbbbbbbbbbbbbbbbbbbbbbb &&
ccccccccccccccccccccccccc &&
ddddddddddddddddddddddddd &&
eeeeeeeeeeeeeeeeeeeeeeeee)();
// Prettier 1.19
(
aaaaaaaaaaaaaaaaaaaaaaaaa &&
bbbbbbbbbbbbbbbbbbbbbbbbb &&
ccccccccccccccccccccccccc &&
ddddddddddddddddddddddddd &&
eeeeeeeeeeeeeeeeeeeeeeeee
)();
Formatierung langer benannter Exports korrigiert (#6446 von @sosukesuzuki)
Benannte Exports werden nun wie benannte Imports formatiert.
// Input
export { fooooooooooooooooooooooooooooooooooooooooooooooooo } from "fooooooooooooooooooooooooooooo";
// Prettier 1.18
export {
fooooooooooooooooooooooooooooooooooooooooooooooooo
} from "fooooooooooooooooooooooooooooo";
// Prettier 1.19
export { fooooooooooooooooooooooooooooooooooooooooooooooooo } from "fooooooooooooooooooooooooooooo";
Fehlerhafte Formatierung bei mehrzeiligem Optional Chaining mit Kommentar behoben (#6506 von @sosukesuzuki)
// Input
return a
.b()
.c()
// Comment
?.d()
// Prettier 1.18
return a
.b()
.c()
?.// Comment
d();
// Prettier 1.19
return (
a
.b()
.c()
// Comment
?.d()
);
Inkonsistente Einrückung in switch-Anweisungen korrigiert (#6514 von @sosukesuzuki)
// Input
switch ($veryLongAndVeryVerboseVariableName && $anotherVeryLongAndVeryVerboseVariableName) {
}
switch ($longButSlightlyShorterVariableName && $anotherSlightlyShorterVariableName) {
}
// Prettier 1.18
switch (
$veryLongAndVeryVerboseVariableName &&
$anotherVeryLongAndVeryVerboseVariableName
) {
}
switch (
$longButSlightlyShorterVariableName && $anotherSlightlyShorterVariableName
) {
}
// Prettier 1.19
switch (
$veryLongAndVeryVerboseVariableName &&
$anotherVeryLongAndVeryVerboseVariableName
) {
}
switch (
$longButSlightlyShorterVariableName &&
$anotherSlightlyShorterVariableName
) {
}
Formatierung von Code mit V8-Intrinsiken unterstützen (#6496 von @rreverser)
// Input
function doSmth() {
%DebugPrint
(
foo )
}
// Prettier 1.18
SyntaxError: Unexpected token (2:13)
1 | function doSmth() {
> 2 | %DebugPrint
| ^
// Prettier 1.19
function doSmth() {
%DebugPrint(foo);
}
Objektdestrukturierung in Methodenparametern brach immer in mehrere Zeilen um (#6646 von @ericsakmar)
// Input
const obj = {
func(id, { blog: { title } }) {
return id + title;
},
};
class A {
func(id, { blog: { title } }) {
return id + title;
}
#func(id, { blog: { title } }) {
return id + title;
}
}
// Prettier 1.18
const obj = {
func(
id,
{
blog: { title }
}
) {
return id + title;
}
};
class A {
func(
id,
{
blog: { title }
}
) {
return id + title;
}
#func(
id,
{
blog: { title }
}
) {
return id + title;
}
}
// Prettier 1.19
const obj = {
func(id, { blog: { title } }) {
return id + title;
},
};
class A {
func(id, { blog: { title } }) {
return id + title;
}
#func(id, { blog: { title } }) {
return id + title;
}
}
Numerische Trennzeichen wurden aus BigInt-Literalen entfernt (#6796 von @thorn0)
// Input
const bigints = [200_000n, 0x0000_000An, 0b0111_1111n];
// Prettier 1.18
const bigints = [200000n, 0x0000000an, 0b01111111n];
// Prettier 1.19
const bigints = [200_000n, 0x0000_000an, 0b0111_1111n];
Bessere Formatierung für verschachtelte await-Ausdrücke in Aufrufen (#6856 von @thorn0)
// Input
async function f() {
const admins = (await(db.select('*').from('admins').leftJoin('bla').where('id', 'in', [1,2,3,4]))).map(({id, name})=>({id, name}))
}
// Prettier 1.18
async function f() {
const admins = (await db
.select("*")
.from("admins")
.leftJoin("bla")
.where("id", "in", [1, 2, 3, 4])).map(({ id, name }) => ({ id, name }));
}
// Prettier 1.19
async function f() {
const admins = (
await db
.select("*")
.from("admins")
.leftJoin("bla")
.where("id", "in", [1, 2, 3, 4])
).map(({ id, name }) => ({ id, name }));
}
HTML
template-Elemente nicht umbrechen bei Zeilen unter printWidth (#6284 von @sosukesuzuki)
Zuvor brach Prettier die Zeile mit einem template-Element um, selbst wenn die Zeilenlänge kürzer als printWidth war.
<!-- Input -->
<template>
<template>foo</template>
</template>
<!-- Prettier 1.18 -->
<template>
<template
>foo</template
>
</template>
<!-- Prettier 1.19 -->
<template>
<template>foo</template>
</template>
Script-Tags werden nun als Blöcke formatiert (#6423 von @thorn0)
Im Whitespace-sensitive-Modus wurden sie zuvor inline formatiert.
<!-- Input -->
<script
async
src="/_next/static/development/pages/_app.js?ts=1565732195968"
></script><script></script>
<!-- Prettier 1.18 -->
<script
async
src="/_next/static/development/pages/_app.js?ts=1565732195968"
></script
><script></script>
<!-- Prettier 1.19 -->
<script
async
src="/_next/static/development/pages/_app.js?ts=1565732195968"
></script>
<script></script>
Unterstützung für ! und andere Entities hinzugefügt (#6785 von @lydell und @ikatyang)
Bisher unterstützte Prettier nur die gängigsten HTML-Entitäten wie und ". Nun unterstützt Prettier jede HTML-Entität gemäß HTML-Spezifikation, etwa ! oder ⋔.
<!-- Input -->
<p>Hi!</p>
<!-- Prettier 1.18
[error] stdin: SyntaxError: Unknown entity "excl" - use the ";" or "<hex>;" syntax (1:6)
[error] > 1 | <p>Hi!</p>
[error] | ^
[error] 2 |
-->
<!-- Prettier 1.19 -->
<p>Hi!</p>
Unterstützung für JSON-Script-Typen hinzugefügt (#6293 by @ascorbic)
<!-- Input -->
<script type="application/json">
{ "json":true }
</script>
<script type="importmap">
{ "json":true }
{ "json":true }
</script>
</script>
<script type="systemjs-importmap">
{ "json":true }
</script>
<!-- Prettier 1.18 -->
<script type="application/json">
{ "json":true }
</script>
<script type="importmap">
{ "json":true }
{ "json":true }
</script>
</script>
<script type="systemjs-importmap">
{ "json":true }
</script>
<!-- Prettier 1.19 -->
<script type="application/json">
{ "json": true }
</script>
<script type="importmap">
{ "json": true }
</script>
<script type="systemjs-importmap">
{ "json": true }
</script>
Angular
Schließende Klammer nach Ternär-Operatoren in Pipes in neue Zeile setzen (#5682 by @selvazhagan)
<!-- Input -->
{{ (isCustomDiscount ? 'DISCOUNTS__DISCOUNT_TRAINING_HEADER__CUSTOM_DISCOUNT' : 'DISCOUNTS__DISCOUNT_TRAINING_HEADER__DISCOUNT') | translate }}
<!-- Prettier 1.18 -->
{{
(isCustomDiscount
? "DISCOUNTS__DISCOUNT_TRAINING_HEADER__CUSTOM_DISCOUNT"
: "DISCOUNTS__DISCOUNT_TRAINING_HEADER__DISCOUNT") | translate
}}
<!-- Prettier 1.19 -->
{{
(isCustomDiscount
? "DISCOUNTS__DISCOUNT_TRAINING_HEADER__CUSTOM_DISCOUNT"
: "DISCOUNTS__DISCOUNT_TRAINING_HEADER__DISCOUNT"
) | translate
}}
Formatierung für i18n-Attribute hinzugefügt (#6695 by @voithos)
Prettier umbricht den Inhalt von i18n-Attributen automatisch, sobald die Zeilenlänge überschritten wird.
<!-- Input -->
<h1 i18n="This is a very long internationalization description text, exceeding the configured print width">
Hello!
</h1>
<!-- Prettier 1.18 -->
<h1
i18n="This is a very long internationalization description text, exceeding the configured print width"
>
Hello!
</h1>
<!-- Prettier 1.19 -->
<h1
i18n="
This is a very long internationalization description text, exceeding the
configured print width
"
>
Hello!
</h1>
Handlebars
Behandlung von Leerzeichen und Zeilenumbrüchen korrigiert (#6354 by @chadian)
Dies behebt verschiedene Probleme bei der Verwendung von Leerzeichen und Zeilenumbrüchen in Handlebars- und Glimmer-Templates.
<!-- Input -->
<SomeComponent />{{name}}
Some sentence with {{dynamic}} expressions.
sometimes{{nogaps}}areimportant<Hello></Hello>
{{name}} is your name
<!-- Prettier 1.18 -->
<SomeComponent />
{{name}}
Some sentence with
{{dynamic}}
expressions.
sometimes
{{nogaps}}
areimportant
<Hello />
{{name}}
is your name
<!-- Prettier 1.19 -->
<SomeComponent />{{name}}
Some sentence with {{dynamic}} expressions.
sometimes{{nogaps}}areimportant
<Hello />
{{name}} is your name
Unerwünschte Zeilenumbrüche zwischen Text und Mustaches vermeiden (#6186 by @gavinjoyce)
Bisher fügte Prettier Zeilenumbrüche zwischen Text und Mustaches ein, was zu unerwünschten Leerzeichen im gerenderten Ergebnis führte.
<!-- Input -->
<p>Your username is @{{name}}</p>
<p>Hi {{firstName}} {{lastName}}</p>
<!-- Prettier 1.18 -->
<p>
Your username is @
{{name}}
</p>
<p>
Hi
{{firstName}}
{{lastName}}
</p>
<!-- Prettier 1.19 -->
<p>
Your username is @{{name}}
</p>
<p>
Hi {{firstName}} {{lastName}}
</p>
Kommentarformatierung verbessert (#6206 by @gavinjoyce)
<!-- Input -->
<div>
{{! Foo }}
{{#if @foo}}
Foo
{{/if}}
{{! Bar }}
{{#if @bar}}
Bar
{{/if}}
</div>
<!-- Prettier 1.18 -->
<div>
{{! Foo }}
{{#if @foo}}
Foo
{{/if}}{{! Bar }}{{#if @bar}}
Bar
{{/if}}
</div>
<!-- Prettier 1.19 -->
<div>
{{! Foo }}
{{#if @foo}}
Foo
{{/if}}
{{! Bar }}
{{#if @bar}}
Bar
{{/if}}
</div>
HTML-Entitäten erhalten (#6234 by @gavinjoyce)
<!-- Input -->
<p>
Some escaped characters: < > &
</p>
<!-- Prettier 1.18 -->
<p>
Some escaped characters: < > &
</p>
<!-- Prettier 1.19 -->
<p>
Some escaped characters: < > &
</p>
Korrektur der --single-quote-Option bei HTML-Attributen (#6377 by @dcyriller)
Bisher wurde die Option nicht auf HTML-Attribute angewendet.
<!-- Input -->
<div class="a-class-name"></div>
<!-- Prettier 1.18, with the option --single-quote -->
<div class="a-class-name"></div>
<!-- Prettier 1.19, with the option --single-quote -->
<div class='a-class-name'></div>
Lange Interpolationen umbrechen (#6249 by @jjaffeux)
<!-- Input -->
{{my-component foo="bar" bar="baz" action=(action "almostTheMaximumLengthxxxx")
}}
<!-- Prettier 1.18 -->
{{my-component foo="bar" bar="baz" action=(action "almostTheMaximumLengthxxxx")
}}
<!-- Prettier 1.19 -->
{{my-component
foo="bar"
bar="baz"
action=(action "almostTheMaximumLengthxxxx")
}}
MDX
Text nach JSX wurde fälschlich gekürzt (#6340 by @JounQin)
<!-- Input -->
<Hello>
test <World /> test
</Hello> 123
<!-- Prettier 1.18 -->
<Hello>
test <World /> test
</Hello>123
<!-- Prettier 1.19 -->
<Hello>
test <World /> test
</Hello> 123
Benachbarte JSX-Elemente sollten erlaubt sein (#6332 by @JounQin)
// Input
<Hello>
test <World /> test
</Hello>123
// Prettier 1.18
SyntaxError: Unexpected token (3:9)
1 | <Hello>
2 | test <World /> test
> 3 | </Hello>123
| ^
// Prettier 1.19
<Hello>
test <World /> test
</Hello>123
// Input
<Hello>
test <World /> test
</Hello>
<Hello>
test <World /> test
</Hello>123
// Prettier 1.18
SyntaxError: Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...</>? (4:1)
2 | test <World /> test
3 | </Hello>
> 4 | <Hello>
| ^
5 | test <World /> test
6 | </Hello>123
// Prettier 1.19
<Hello>
test <World /> test
</Hello>
<Hello>
test <World /> test
</Hello>123
Vue
Formatierung von style[lang="css"] (#6875 by @fisker)
Bisher wurden <style>-Elemente mit lang="css" nicht formatiert, während das Weglassen des Attributs oder andere Werte funktionierten. Dieser Versehen wurde behoben.
<!-- Input -->
<style lang="css">
a {
color: #F00
}</style>
<!-- Output (Prettier stable) -->
<style lang="css">
a {
color: #F00
}
</style>
<!-- Output (Prettier master) -->
<style lang="css">
a {
color: #f00;
}
</style>
Less
Variablennamen nicht kleinschreiben und Leerzeichen zwischen Variable und Doppelpunkt entfernen (#6778 by @fisker)
// Input
@FoO : bar;
// Prettier 1.18
@foo : bar;
// Prettier 1.19
@FoO: bar;
API
resolveConfig-Option zu getFileInfo() hinzugefügt (#6666 by @kaicataldo)
Fügt eine resolveConfig: boolean-Option zu prettier.getFileInfo() hinzu, die, wenn auf true gesetzt, die Konfiguration für den angegebenen Dateipfad auflöst. Dadurch können übergreifende Parser berücksichtigt werden.
CLI
Fehlerbehandlung beim Lesen von stdin (#6708 by @andersk and @lydell)
Bei Fehlern in .prettierrc stürzte Prettier bisher beim Formatieren von stdin ab. Solche Fehler werden nun korrekt behandelt.
# Prettier 1.18
$ prettier --parser babel < test.js
(node:21531) UnhandledPromiseRejectionWarning: Error: Invalid printWidth value. Expected an integer, but received "nope".
at _loop (/home/you/project/node_modules/prettier/bin-prettier.js:7887:63)
at Normalizer._applyNormalization (/home/you/project/node_modules/prettier/bin-prettier.js:8000:13)
at applyNormalization (/home/you/project/node_modules/prettier/bin-prettier.js:7817:49)
at Normalizer.normalize (/home/you/project/node_modules/prettier/bin-prettier.js:7823:9)
at normalizeOptions$1 (/home/you/project/node_modules/prettier/bin-prettier.js:8760:31)
at Object.normalizeApiOptions (/home/you/project/node_modules/prettier/bin-prettier.js:8918:10)
at getOptionsForFile (/home/you/project/node_modules/prettier/bin-prettier.js:44160:69)
at /home/you/project/node_modules/prettier/bin-prettier.js:44214:22
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:21531) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:21531) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
# Prettier 1.19
$ prettier --parser babel < test.js
[error] Invalid printWidth value. Expected an integer, but received "nope".
Elegante Behandlung nicht existierender Pfade bei --stdin-filepath (#6687 by @voithos and @lydell)
Bisher führte die Übergabe eines nicht existierenden Unterverzeichnisses an --stdin-filepath zu einem Fehler. Nun geht Prettier damit elegant um.
# Prettier 1.18
$ prettier --stdin-filepath does/not/exist.js < test.js
[error] Invalid configuration file: ENOENT: no such file or directory, scandir '/home/you/project/does/not'
# Prettier 1.19
$ prettier --stdin-filepath does/not/exist.js < test.js
test;
Konfiguration sollte nicht für ignorierte Dateien ausgewertet werden (#6233 by @jamesreggio)
Vor dieser Änderung wertete die CLI die Konfiguration für eine Datei aus, bevor sie gegen die Ignore-Liste geprüft wurde. Bei ungültiger Konfiguration meldete die CLI einen Fehler.
Diese Änderung verschiebt die Konfigurationsauswertung auf den Zeitpunkt nach der Bestätigung, dass die Datei nicht ignoriert wird.
Ungültigen Konfigurationsdateinamen in Fehlermeldung anzeigen (#6865 von @fisker)
# Input
$ prettier filename.js --config .invalid-config
# Prettier 1.18
Invalid configuration file: ...
# Prettier 1.19
Invalid configuration file `.invalid-config`: ...
Weitere Änderungen
Vielen Dank an @fisker für die Aktualisierung zahlreicher Abhängigkeiten von Prettier!
VS Code: Unterstützung für .mongo-Dateien hinzugefügt (#6848 von @aymericbouzy)
Bei Verwendung der Azure Cosmos DB-Erweiterung für VS Code können Sie .mongo-Dateien erstellen, um MongoDB-Abfragen zu schreiben, die JavaScript-Syntax verwenden. Diese Änderung ermöglicht es VS Code, Ihre Dateien mit Prettier zu formatieren.
db.users.find({ someField: { $exists: true } });
