Node.jsのコードをPrettierでフォーマットしてESLintにかける
node.jsPrettierはJSやTSのコードフォーマッタで、 ReactやBabel、Yarnなどの開発にも使われている。
今回はPrettierでフォーマットしたものを eslint –fix するprettier-eslint-cliを使う。役割が被っているがPrettierは eslint –fix よりも強力にフォーマットしてくれるようだ。
$ git init
$ yarn add --dev eslint eslint-config-google prettier-eslint-cli husky lint-staged
$ cat .eslintrc.js
module.exports = {
"extends": "google",
"parserOptions": {
"ecmaVersion": 2017,
}
};
対象のコードはこれ。
$ cat src/main.js
/**
* hoge function
*/
function hoge() {
const f = (aaaaaaaaaaaaaaa, bbbbbbbbbb, ccccccccc, dddddddddddd, eeeeeeeeeeeeee) =>
console.log('a');
f(1, 2, 3, 4, 5);
}
hoge();
Prettierのドキュメントでも紹介されているようにlint-stagedを使うとCommit時にフォーマットし、Lintをかけることができる。
{
"scripts": {
"precommit": "lint-staged",
"lint": "eslint src",
"format": "prettier-eslint --write \"src/**/*.js\""
},
"lint-staged": {
"*.js": [
"prettier-eslint --write",
"eslint",
"git add"
]
},
"devDependencies": {
"eslint": "^4.9.0",
"eslint-config-google": "^0.9.1",
"husky": "^0.14.3",
"lint-staged": "^4.2.3",
"prettier-eslint-cli": "^4.4.0"
}
}
$ git commit -m "test"
husky > npm run -s precommit (node v8.2.1)
✔ Running tasks for *.js
[master e325ea3] test
$ cat src/main.js
/**
* hoge function
*/
function hoge() {
const f = (
aaaaaaaaaaaaaaa,
bbbbbbbbbb,
ccccccccc,
dddddddddddd,
eeeeeeeeeeeeee
) => console.log('a');
f(1, 2, 3, 4, 5);
}
hoge();
Prettierは eslint –fix で修正されないmax-lenも良い感じにしてくれる。 なのでESLintのフォーマットに関するところはほとんど修正いらないはず。
$ git commit -m "test"
husky > npm run -s precommit (node v8.2.1)
❯ Running tasks for *.js
✖ eslint --fix
git add
✖ eslint --fix found some errors. Please fix them and try committing again.
***/src/main.js
5:1 error Line 5 exceeds the maximum line length of 80 max-len
✖ 1 problem (1 error, 0 warnings)