1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

.prettierrcをymlで書く

Last updated at Posted at 2022-01-30

はじめに

コードの見た目を整えるためのPrettierの設定ファイルをYAML形式で書いてみたかったので、備忘録として残しておく。

設定項目

公式ドキュメントを参照しつつ、Prettierの設定項目を表形式でまとめる。

項目名 デフォルト値 概要
printWidth 80 1行の長さ。この設定値を超えると改行される。
tabWidth 2 インデントレベルごとのスペース数。
useTabs false スペースではなくタブで行をインデントする。
semi true 文の末尾にセミコロンを追加する。
singleQuote false 文字列をシングルクォートで囲むかどうか。JSXはこのオプションを無視する。
jsxSingleQuote false ↑ のJSX版。
trailingComma "es5" 複数行のカンマ区切り構文構造における末尾のカンマ表示。
  • "es5": ES5(オブジェクトや配列)で有効なカンマを追加する
  • "none": 末尾にカンマを追加しない
  • "all": 関数のパラメータや呼び出しを含み、可能な限り末尾にカンマを追加する
bracketSpacing true オブジェクトリテラルに含まれるカッコのスペースを追加。
  • true: { foo: bar }
  • false: {foo: bar}
bracketSameLine false 複数行に渡るHTML要素の>を最終行の最後に置くか、その次の行に単独で置くか。
arrowParens "always" アロー関数の引数が一つの場合、括弧で囲むかどうか。
  • "always": (x) => x
  • "avoid": x => x
requirePragma false ファイルの先頭にプラグマと呼ばれる特別なコメントを含むファイルのみをフォーマットするよう制限することができる。大規模な未フォーマットのコードを徐々にPrettierでフォーマットしていく際に有効。

Playground

Prettierの公式サイトでは、どのようにコードをフォーマットできるか、各項目を設定して試すことができるのでオススメです。
playground.png

設定ファイル

自分の場合、以下のような設定ファイルにしました。
YAMLだと文字列はクォートで囲っても囲わなくてもいいため、今回は囲っていません。

.prettierrc.yml
arrowParens: always
bracketSameLine: false
bracketSpacing: true
jsxSingleQuote: true
printWidth: 80
requirePragma: true
semi: true
singleQuote: true
tabWidth: 2
trailingComma: all
useTabs: false

JSONだと以下です。

prettierrc.json
{
  "arrowParens": "always",
  "bracketSameLine": false,
  "bracketSpacing": true,
  "jsxSingleQuote": true,
  "printWidth": 80,
  "requirePragma": true,
  "semi": true,
  "singleQuote": true,
  "tabWidth": 2,
  "trailingComma": "all",
  "useTabs": false,
}

実行

まだフォーマットされていないファイルを調べたい場合には、--checkオプションを使い、

ターミナル
% npx prettier --check .
Checking formatting...
[warn] hoge.js
[warn] bar.json
[warn] ...

実際にフォーマットを実行する場合には、--writeオプションを使う。

ターミナル
% npx prettier --write src/components/Hoge/index.tsx

requirePragma: trueにした場合は、ファイルの先頭に

/**
 * @prettier
 */

を付けないと整形してくれません。

VSCodeでファイル保存時に整形する場合は、以下のように、Default FormatterをPrettierに設定した上で、
vscode.png
Format On Saveを有効にする必要があります。
vscode_format-on-save.png

以上です。間違い等あればご指摘いただけると嬉しいです!

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?