$ npm init -y
$ npm install -D prettier lint-staged husky
precommit と lint-staged を追加
{
"scripts": {
"precommit": "lint-staged"
},
"lint-staged": {
"*.js": [
"prettier --write",
"git add"
]
}
}
.git/hooks/pre-commit
#!/bin/sh
npm run precommit
exit 0
コミットしてみる
index.js(コミット前)
const foo = {
a: 1,
b: 2,
c: 3,
}
const bar = {c:'d'}
const baz = ["foo", "bar", "baz", "foo", "bar", "baz", "foo", "bar", "baz", "foo", "bar", "baz"]
console.info(foo)
console.info(bar)
console.info(baz)
コミットして見る
$ git add index.js
$ git commit -m "add index.js"
index.js(コミット後)
const foo = {
a: 1,
b: 2,
c: 3
};
const bar = { c: "d" };
const baz = [
"foo",
"bar",
"baz",
"foo",
"bar",
"baz",
"foo",
"bar",
"baz",
"foo",
"bar",
"baz"
];
console.info(foo);
console.info(bar);
console.info(baz);
おまけ
prettier の整形の設定は6個くらい
(gofmt は変更できる設定は0)
$ node_modules/.bin/prettier --help
Usage: prettier [opts] [filename ...]
Available options:
--write Edit the file in-place. (Beware!)
--list-different or -l Print filenames of files that are different from prettier formatting
--stdin Read input from stdin.
--print-width <int> Specify the length of line that the printer will wrap on. Defaults to 80.
--tab-width <int> Specify the number of spaces per indentation-level. Defaults to 2.
--single-quote Use single quotes instead of double.
--bracket-spacing Put spaces between brackets. Defaults to true.
--jsx-bracket-same-line Put > on the last line. Defaults to false.
--trailing-comma <none|es5|all>
Print trailing commas wherever possible. Defaults to none.
--parser <flow|babylon> Specify which parse to use. Defaults to babylon.
--color Colorize error messages. Defaults to true.
--version or -v Print prettier version.
Boolean options can be turned off like this:
--no-bracket-spacing
--bracket-spacing=false
追記
配列を改行したくても1行になったりのケース
デフォルトで –print-width 80 だとそれ以下の文字数の場合に改行してると1行に変換されてしまう。
整形前
const baz = [
"foo",
"bar",
"baz",
"foo",
"bar",
"baz",
]
整形後
const baz = ["foo", "bar", "baz", "foo", "bar", "baz", "foo", "bar", "baz"];
Reactのソースコードで使われてるらしいけど
感想
- prettier 使わずに eslint でチェックしつつコード書くでもいいかも?
- eslintrc –fix でもいいような気がしてきた
- 既存コードを大量に整形しないといけないとかだったら prettier 便利かも
参考