This repository is configured to run tsc and prettier before every commit.
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".
We need to create two files:
{
"printWidth": 120,
"proseWrap": "preserve",
"semi": false,
"singleQuote": true,
"useTabs": false,
"tabWidth": 2,
"arrowParens": "avoid",
"trailingComma": "es5"
}
node_modules;
build;
dist;
res;
coverage;
You can of course configure this in any way you like.
{
"**/*.+(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).
{
"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.
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.
I've setup a very basic repository on GitHub as a demo.