We can easily improve our developer experience by:
- Preventing broken code being committed/pushed.
- Avoiding pointless arguments about formatting in our code reviews.
We decided to use git pre-commit hooks to help prevent "broken" commits.
We started from an existing TypeScript project, but here's a demo repository if you want to have a look.
1. Install prettier, husky and lint-staged
yarn add -D prettier husky lint-staged
None of these are required at run time so it's important to use -D
so that the dependencies are added to "devDependencies".
2. Configure prettier
We need to create two files:
.prettierrc:
{
"printWidth": 120,
"proseWrap": "preserve",
"semi": false,
"singleQuote": true,
"useTabs": false,
"tabWidth": 2,
"arrowParens": "avoid",
"trailingComma": "es5"
}
.prettierignore:
node_modules
build
dist
res
coverage
You can of course configure this in any way you like.
3. Create a lint-staged config file: .lintstagedrc:
{
"**/*.+(js|jsx|css|less|scss|ts|tsx|md)": [
"prettier --write",
"git add"
]
}
This is configured to run prettier and overwrite any staged files that match the pattern above and then staging the new changes (if any).
4. Create a husky config file: .huskyrc:
{
"hooks": {
"pre-commit": "tsc && lint-staged"
}
}
This is configuring the pre-commit hook. It will run tsc
and then lint-staged
using the configuration files discussed above.
5. Success!
Now every time I try to commit, the pre-commit hook will run.
If -for some reason- my code doesn't compile I'll get an error and a chance to fix it before committing.
And I don't have to worry about code formatting because prettier
will format any staged files before committing.
Demo Repository
I've setup a very basic repository on GitHub as a demo.
Photo by Simon Wilkes on Unsplash
Top comments (3)
Hi Julian, thanks for the guide. I want to ask how to use
Airbnb style guide
withlint-staged
. Do you have any resources you can point me to?Hi Adeyemi, I'm afraid I haven't tried this with Airbnb style guide, but if you have it configured as a linter, you can probably change the
.lintstagedrc
file to specify different linters to different file types.You could try something like this:
.lintstagedrc
Thanks a lot for the tip. I will try it out