メインコンテンツへスキップ

Prettier 1.19: 待望のVueオプション、TypeScript 3.7サポート、新JavaScript機能

· 1分で読める
非公式ベータ版翻訳

このページは PageTurner AI で翻訳されました(ベータ版)。プロジェクト公式の承認はありません。 エラーを見つけましたか? 問題を報告 →

今回のリリースでは待望の--vue-indent-script-and-styleオプションの追加、TypeScript 3.7のサポート、最先端のJavaScript構文に対応しました。さらに数多くのバグ修正と改善も含まれています!

主な変更点

Vue

--vue-indent-script-and-styleの追加 (#6157 by @kamilic)

新しく追加された--vue-indent-script-and-styleオプションは、Vueファイル内の<script>タグと<style>タグ内のコードをインデントするかどうかを制御します。Vueの作者のようにインデントレベルを節約するためにインデントしない選択肢もありますが、これはエディタのコード折りたたみ機能を壊す可能性があります。この変更は当プロジェクトで最もコメント数の多かったIssueを解決し、多くのVue開発者の開発体験を向上させるでしょう!

TypeScript

TypeScript 3.7のサポート (#6657 by @cryrivers)

Prettier 1.19では、近日公開予定のTypeScript 3.7で導入される新構文機能に対応しました:

(注記:TypeScript 3.7の依存関係アップグレードに伴い、GitHubからの直接インストールではNode.js 6のサポートが終了しました。npm経由でインストールしたPrettierは引き続きNode.js 4との互換性を維持します)

オプショナルチェイニング
// 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);
Null合体演算子
// 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";
アサーション関数
// 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修飾子
// 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

部分適用構文のサポート追加 (#6397 by @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\`.

関数合成の検出に引数内の関数リテラルを使用 (#6033 by @brainkim)

以前は、関数合成やチェーンパターンを検出するために、関数型プログラミングに関連するハードコードされた名前セット(compose, flow, pipeなど)を使用していました。これは、以下のpipe呼び出しのように、許容カラム幅に収まる場合でも同じ行に配置しないようにするためでした:

source$
.pipe(
filter(x => x % 2 === 0),
map(x => x + x),
scan((acc, x) => acc + x, 0),
)
.subscribe(x => console.log(x));

しかしこのヒューリスティックは、関数引数を含まない呼び出しでも、ハードコードされた名前に一致する関数やメソッドの呼び出しが常に複数行に分割されるという誤検出(#5769, #5969)により不満の声が上がっていました。多くの開発者にとって、名前ベースの一律分割判断は予想外で最適とは言えないものでした。

現在は関数リテラルの存在を検出する改良版ヒューリスティックを採用しています。これにより上記の行分割動作を維持しつつ、旧ヒューリスティックによる誤検出をほぼ完全に排除しています。

ぜひお試しいただき、フィードバックをお寄せください!

// 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));

一部ケースでパースエラーがあってもフォーマットを実行可能に (#6816 by @thorn0 and the Babel team)

Babelパーサーを最新版に更新し、素晴らしい機能を追加しました。Prettierは一部の無効なコードでもフォーマット可能になり、コーディング体験がよりスムーズになります。Babelがエラー回復パース機能を改善するにつれ、この機能はさらに向上するでしょう。詳細はBabel 7.7.0のブログ記事をご覧ください!

// 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;

その他の変更点

TypeScript

オプションの計算済みクラスフィールドとメソッドを修正 (#6657 by @cryrivers, #6673 by @thorn0)

キーが複雑な式の場合は未修正ですが、以下のケースでは修正されました:

// 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]?() {}
}

型引数付きJSX要素名の後のコメントが失われる問題を修正 (#6209 by @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>
);

JSXテキスト内で//使用時のクラッシュを修正 (#6289 by @duailibe)

このバージョンではTypeScriptパーサーを更新し、JSXテキスト内のダブルスラッシュ(//)を正しく処理できるようになりました。以前のバージョンではPrettierがクラッシュしていました。

長い1行のマップ型を1回のパスで正しくフォーマット (#6420 by @sosukesuzuki)

以前は長い1行のマップ型をフォーマットする際、行を分割してもセミコロンが追加されず、Prettierを再度実行する必要がありました(冪等性の破れ)。現在は初回実行時からセミコロンが追加されます。

// 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];
};

変数宣言の型注釈で型パラメータをインラインに維持 (#6467 by @sosukesuzuki)

// Input
const fooooooooooooooo: SomeThing<boolean> = looooooooooooooooooooooooooooooongNameFunc();

// Prettier 1.18
const fooooooooooooooo: SomeThing<
boolean
> = looooooooooooooooooooooooooooooongNameFunc();

// Prettier 1.19
const fooooooooooooooo: SomeThing<boolean> = looooooooooooooooooooooooooooooongNameFunc();

型を囲む二重括弧が誤って削除されるケースを修正 (#6604 by @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"];

構文エラー回避のため必要な場合にJSXを囲む括弧を維持 (#6640 by @sosukesuzuki)

// Input
(<a />).toString();

// Prettier 1.18
<a />.toString():

// Prettier 1.19
(<a />).toString();

no-semi有効時でもインデックスシグネチャ前のクラスプロパティのセミコロンを維持 (#6728 by @sosukesuzuki)

以前はPrettierの出力を再度フォーマットすると構文エラーが発生していました。

// 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
}

as型式を使用した引数展開を改善 (#6471 by @mattleff)

以前はas型式や型アサーションを含む呼び出し式をフォーマットする際、行が分割されていました。現在はas型/型アサーション内の式を基に改行を決定します。

// 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

タプル内のユニオン型インデントを修正 (#6381 by @squidfunk, #6605 by @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
]
];

useEffectのような関数呼び出しでのコメント移動を修正 (#6270 by @sosukesuzuki)

この修正は、アロー関数を第1引数、配列式を第2引数とする関数呼び出し(例: ReactのuseEffect)に影響するバグに対処します。以前は第2引数の前の行にあるコメントが不正に移動され、インデントが崩れていました。

このバグはFlowとTypeScriptパーサー使用時のみ発生していました。

// 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
[]
);

ユニオン型後の閉じ括弧を改行して配置 (#6307 by @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

enumのサポートを追加 (#6833 by @gkz)

// Input
enum E of string {
A = "a",
B = "b",
}

// Prettier 1.19
enum E of string {
A = "a",
B = "b",
}

ObjectTypeAnnotation内のFunctionTypeAnnotationを含むアロー関数の戻り値型に括弧を追加 (#6717 by @sosukesuzuki)

これはFlowパーサーのバグに対する回避策です。括弧がないとパーサーエラーが発生します。

// 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

各要素が複数の要素/プロパティを持つ場合、配列の配列/オブジェクトを分割 (#6694 by @sosukesuzuki)

これにより、new Map や Jest の test.each 呼び出しがより適切にフォーマットされるようになります。

// 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]
]);

?? の優先順位をステージ3提案に合わせて更新 (#6404 by @vjeux, #6863 by @jridgewell)

Nullish coalescing演算子のサポートを、&&|| 演算と直接組み合わせることを許可しなくなった仕様変更に合わせて更新しました。

// 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;

注意: この仕様変更をサポートするパーサーに更新したため、括弧なしのコードはパースエラーとなります。

同一演算子の論理式で括弧を不要に (#6864 by @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;

new 呼び出しの括弧を可読性向上 (#6412 by @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)();

単項式内のコメント付き括弧を保持 (#6217 by @sosukesuzuki)

// Input
!(
/* foo */
foo
);
!(
foo // foo
);

// Prettier 1.18
!/* foo */
foo;
!foo; // foo

// Prettier 1.19
!(/* foo */ foo);
!(
foo // foo
);

タグ付きテンプレートリテラル内のコメント移動を停止 (#6236 by @sosukesuzuki)

// Input
foo //comment
`
`;

// Prettier 1.18
foo` // comment
`;

// Prettier 1.19
foo // comment
`
`;

分割代入されたアロー関数パラメータ内の空行がインデントと冪等性を破壊する問題を修正 (#6301 & #6382 by @sosukesuzuki)

以前は、オブジェクトパターンを含むパラメータを持つアロー関数が関数呼び出しの引数として渡される場合に、Prettierが不自然なインデントを生成し、冪等性も損なわれていました。詳細は#6294をご覧ください。

// Input
foo(
({
a,

b
}) => {}
);

// Prettier 1.18
foo(({ a,
b }) => {});

// Prettier 1.19
foo(
({
a,

b
}) => {}
);

パラメータデコレータ付きオブジェクト分割代入のフォーマットを修正 (#6411 by @sosukesuzuki)

// Input
class Class {
method(
@decorator
{ foo }
) {}
}

// Prettier 1.18
class Class {
method(@decorator
{
foo
}) {}
}

// Prettier 1.19
class Class {
method(
@decorator
{ foo }
) {}
}

関数パラメータ内の型注釈付き空オブジェクトパターンの処理 (#6438 by @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) {}

関数呼び出し内の二項式後に閉じ括弧を改行 (#6441 by @sosukesuzuki)

// Input
(
aaaaaaaaaaaaaaaaaaaaaaaaa &&
bbbbbbbbbbbbbbbbbbbbbbbbb &&
ccccccccccccccccccccccccc &&
ddddddddddddddddddddddddd &&
eeeeeeeeeeeeeeeeeeeeeeeee
)();

// Prettier 1.18
(aaaaaaaaaaaaaaaaaaaaaaaaa &&
bbbbbbbbbbbbbbbbbbbbbbbbb &&
ccccccccccccccccccccccccc &&
ddddddddddddddddddddddddd &&
eeeeeeeeeeeeeeeeeeeeeeeee)();

// Prettier 1.19
(
aaaaaaaaaaaaaaaaaaaaaaaaa &&
bbbbbbbbbbbbbbbbbbbbbbbbb &&
ccccccccccccccccccccccccc &&
ddddddddddddddddddddddddd &&
eeeeeeeeeeeeeeeeeeeeeeeee
)();

長い名前付きエクスポートのフォーマットを修正 (#6446 by @sosukesuzuki)

これでPrettierは名前付きエクスポートを名前付きインポートと同じ方法でフォーマットします。

// Input
export { fooooooooooooooooooooooooooooooooooooooooooooooooo } from "fooooooooooooooooooooooooooooo";

// Prettier 1.18
export {
fooooooooooooooooooooooooooooooooooooooooooooooooo
} from "fooooooooooooooooooooooooooooo";

// Prettier 1.19
export { fooooooooooooooooooooooooooooooooooooooooooooooooo } from "fooooooooooooooooooooooooooooo";

コメント付き複数行オプショナルチェイニングの不適切なフォーマットを修正 (#6506 by @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()
);

switch文内のインデント不整合を修正 (#6514 by @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
) {
}

V8組み込み関数を含むコードのフォーマットをサポート (#6496 by @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);
}

メソッドパラメータ内のオブジェクト分割代入が常に複数行に分割される問題を修正 (#6646 by @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;
}
}

BigIntリテラルから数値セパレータが削除される問題を修正 (#6796 by @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];

呼び出し内にネストされたインラインawait式のフォーマット改善 (#6856 by @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

printWidthより短い行のtemplate要素を折り返さない (#6284 by @sosukesuzuki)

以前は行の長さがprintWidthより短くても、Prettierはtemplate要素で行を分割していました。

<!-- Input -->
<template>
<template>foo</template>
</template>

<!-- Prettier 1.18 -->
<template>
<template
>foo</template
>
</template>

<!-- Prettier 1.19 -->
<template>
<template>foo</template>
</template>

scriptタグをフォーマット目的でブロックとして扱うように変更 (#6423 by @thorn0)

以前は空白を保持するモードでインライン要素のようにフォーマットされていました。

<!-- 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>

&excl;などのHTML実体参照をサポート追加 (#6785 by @lydell and @ikatyang)

以前はPrettierは&nbsp;&quot;など主要なHTML実体参照のみをサポートしていました。現在はHTML仕様のすべての実体参照(&excl;&pitchfork;など)をサポートします。

<!-- Input -->
<p>Hi&excl;</p>

<!-- Prettier 1.18
[error] stdin: SyntaxError: Unknown entity "excl" - use the "&#;" or "&#x<hex>;" syntax (1:6)
[error] > 1 | <p>Hi&excl;</p>
[error] | ^
[error] 2 |
-->

<!-- Prettier 1.19 -->
<p>Hi&excl;</p>

JSONスクリプトタイプを追加 (#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

パイプに渡された三項演算子の後に閉じ括弧を改行するように変更 (#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
}}

i18n属性のフォーマットを追加 (#6695 by @voithos)

Prettierはi18n属性の内容が行の長さを超えた場合、自動的に折り返すようになります。

<!-- 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

空白と改行の処理を修正 (#6354 by @chadian)

HandlebarsおよびGlimmerテンプレート内での様々な空白と改行のユースケースに対応しました。

<!-- 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

テキストとMustacheタグ間の不要な改行追加を回避 (#6186 by @gavinjoyce)

以前はPrettierがテキストとMustacheタグの間に改行を追加し、レンダリング結果に不要な空白が生じていました。

<!-- 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>

コメントフォーマットを改善 (#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エンティティを保持 (#6234 by @gavinjoyce)

<!-- Input -->
<p>
Some escaped characters: &lt; &gt; &amp;
</p>

<!-- Prettier 1.18 -->
<p>
Some escaped characters: < > &
</p>

<!-- Prettier 1.19 -->
<p>
Some escaped characters: &lt; &gt; &amp;
</p>

HTML属性での--single-quoteオプション適用を修正 (#6377 by @dcyriller)

以前はこのフラグがHTML属性に適用されていませんでした。

<!-- 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>

長い補間式を改行 (#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

JSXに続くテキストのトリミング誤りを修正 (#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

隣接するJSX要素を許可 (#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

style[lang="css"]のフォーマットをサポート (#6875 by @fisker)

以前はlang="css"属性を持つ<style>要素がフォーマット対象外でしたが、属性を省略した場合や他の値では機能していた問題を修正しました。

<!-- 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

変数名の小文字化を停止し、変数とコロンの間の空白を保持 (#6778 by @fisker)

// Input
@FoO : bar;

// Prettier 1.18
@foo : bar;

// Prettier 1.19
@FoO: bar;

API

getFileInfo()resolveConfigオプションを追加 (#6666 by @kaicataldo)

prettier.getFileInfo()resolveConfig: booleanオプションを追加。trueに設定すると指定ファイルパスの設定を解決し、上書きされたパーサーを考慮できるようになります。

CLI

stdin読み取り時のエラー処理を改善 (#6708 by @andersk and @lydell)

.prettierrcにエラーがある場合、stdinのフォーマット時にPrettierがクラッシュしていましたが、適切に処理されるようになりました。

# 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".

--stdin-filepathに存在しないパスが渡された際のグレースフルな処理 (#6687 by @voithos and @lydell)

存在しないサブディレクトリを--stdin-filepathに渡すとエラーが発生していましたが、適切に処理されるようになりました。

# 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;

無視ファイルの設定評価をスキップ (#6233 by @jamesreggio)

以前はCLIが無視リストとの照合前に設定を解決していたため、設定が無効な場合に失敗していました。

ファイルが無視対象でないことを確認した後で設定解決フェーズが行われるように変更されました。

無効な設定ファイル名をエラーメッセージに表示 (#6865 by @fisker)

# Input
$ prettier filename.js --config .invalid-config

# Prettier 1.18
Invalid configuration file: ...

# Prettier 1.19
Invalid configuration file `.invalid-config`: ...

その他

Prettierの多数の依存関係を更新してくれた@fiskerに感謝!

VS Code: .mongoファイルのサポートを追加 (#6848 by @aymericbouzy)

VS Code向けAzure Cosmos DB拡張機能を使用する際、.mongoファイルを作成してJavaScript構文のMongoDBクエリを記述できます。この変更により、VS CodeでPrettierを使用したファイルフォーマットが可能になります。

db.users.find({ someField: { $exists: true } });