Prettier
https://gyazo.com/a73581ce97bc26be232655ae6f2cf40e
https://prettier.io/
Prettier is an opinionated code formatter
(Prettier は意見を持ったコードフォーマッタである)
https://prettier.io/docs/en/why-prettier
そのため、わずかな設定オプションしか提供しない
https://prettier.io/docs/en/options
ESLint との大きな違い
デフォルト値が設定されているので、設定オプションを指定しなくても使える
ただし、Prettier を使っていることが分かるように空の設定ファイルを作成しておくのが良い
code:.prettierrc
{}
メリット
コードの 可読性 を向上させる
コードスタイル の 一貫性 を保つ
対応言語: JavaScript, HTML, CSS, Markdown, GraphQL, YAML, ...
導入
https://prettier.io/docs/en/install
インストール
code:sh
$ npm install --save-dev prettier
.prettierrc の作成
https://prettier.io/docs/en/options
e.g.
code:.prettierrc
{
"singleQuote": true,
"trailingComma": "all",
"printWidth": 80,
"tabWidth": 2,
"semi": true
}
除外したいディレクトリは .prettierignore で指定可能
https://prettier.io/docs/en/ignore.html#ignoring-files-prettierignore
code:.prettierignore
dist
実行
code:sh
$ npx prettier index.js
--write を付けると、ファイルを変更してくれる
code:sh
$ npx prettier --write index.js
package.json の scripts への追加
主に CI で利用する
code:package.json
{
"scripts": {
"test": "jest",
"lint": "eslint . && prettier --list-different .",
"format": "eslint --fix && prettier --loglevel warn --write ."
},
}
--list-different: https://prettier.io/docs/en/cli.html#--list-different
フォーマットの問題があるファイル名をリストアップする
ESLint の動作に一致する
--log-level warn: https://prettier.io/docs/en/cli.html#--log-level
Prettier に問題が発生した場合のみ出力を表示する
これも ESLint の動作に一致する
Visual Studio Code との統合
Visual Studio Code の拡張機能をインストールする
https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode
保存時に走るように、editor.foramtOnSave に true を設定すると良い
code:json
{
...
"editor.formatOnSave": true
}
editor.formatOnType に true を設定すると、タイミング中に走る