So after a brief discussion on #nodejs it looks like people would like:
- To use Prettier to format all our code automagically so it all sticks to one consistent style
- To use XO as a wrapper on ESLint to enforce code-quality rules
- To ditch Standard because as it turns out people like semicolons.
Read the docs on:
- Prettier.io
- xo
- Riffed off Zeit’s implementation of the two, except less Reäct-y.
I ran $ xo
and got over 4000 errors mostly around variable naming and var/let that should have been const
I ran $ xo --fix
and it down to 200 which were around filenames not using the right convention and stuff it doesn't want to auto fix.
But because I worry this would make a huge PR that no one wants to look through I thought we can go introduce the rules incrementally with a precommit hook. So…
I looking harder at [Zeit’s]https://github.com/zeit/now-desktop/issues/266) I noticed they run on pre-commit, Prettier actually has docs on this too.
So I installed Husky and now run prettier --write
and xo --fix
on pre-commit on any files that have been staged for commit.
npm i -D xo prettier eslint-config-prettier husky lint-staged
- Add the xo config to your
package.json
{
"xo": {
"extends": [
"prettier"
],
"ignore": [
"node_modules/**/*.*"
]
},
}
- Add the job that runs precommit:
{
"lint-staged": {
"*.js": [
"xo --fix",
"npm run lint",
"prettier --write",
"git add"
],
"*.css": [
"prettier --write",
"git add"
]
},
}
- Add the precommit job to scrips
{
"scripts":{
"precommit": "lint-staged"
}
}
Then when you do a commit this happens
❯ git commit -m "commit message"
husky > npm run -s precommit (node v6.11.1)
❯ Running tasks for *.js
✖ xo --fix
→ 1 error
npm run lint
prettier --write
git add
↓ Running tasks for *.css [skipped]
→ No staged files match *.css
✖ xo --fix found some errors. Please fix them and try committing again.
app/utils/email_tools.js:1:1
✖ 1:1 Filename is not in kebab case. Rename it to email-tools.js. unicorn/filename-case
1 error
husky > pre-commit hook failed (add --no-verify to bypass)
So now you have your code listed and styled automatically on commit but it's nice to not have your commit rejected so I'd recommend install a linter plugin to your editor so that you get inline highlighting.
XO has plugins for most of the text editors out there. If you use an IDE you can use an ESLint plugin instead.
To make it really easy to get going I've created a boilerplate repo with nothing but a package.json
and an index.js
so that you can just run npm i
and get everything. — https://github.com/jonheslop/nodejs-starter
The pros of this are, repos would graudally meet style rather than having to one big change PR which reformatted everything.
We use https://github.com/alphagov/govuk-lint, but we're keen to have a more general approach that's not tied to Ruby that we can use alongside the community.