Skip to content

Instantly share code, notes, and snippets.

@LiamPerson
Last active July 19, 2023 14:54
Show Gist options
  • Save LiamPerson/0827ad3edfdaf2d7b6b0d0708dcf64b3 to your computer and use it in GitHub Desktop.
Save LiamPerson/0827ad3edfdaf2d7b6b0d0708dcf64b3 to your computer and use it in GitHub Desktop.
How I set up precommits with my nextjs projects to support linting and prettifying my staged files.

Automatic linting + prettifying staged files

Note that this only works for NextJS projects

  • (needed for good eslinting) Add a .eslintrc.json file to the root of your project with the following contents:
{
  "extends": "next/core-web-vitals"
}
  • (optional prettier config) Add a .prettierrc file to the root of your project with the following contents:
{
	"tabWidth": 2,
	"useTabs": true,
	"printWidth": 140,
	"semi": false,
	"singleQuote": true,
	"jsxSingleQuote": true,
	"trailingComma": "es5",
	"bracketSpacing": true,
	"bracketSameLine": false,
	"singleAttributePerLine": true
}
  • install husky, lint-staged, and prettier as dev dependencies
npx husky-init
npm install
npm install --save-dev lint-staged
npm install --save-dev prettier
  • The npx husky-init command should have added a .husky directory to your project. Modify the pre-commit file so it's contents are:
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"

npm run lint
npx lint-staged
  • At the bottom of your package.json add the following:
[...]
  "lint-staged": {
    "*.{js,ts,tsx,json,graphql}": [
      "prettier --write"
    ]
  }
[...]

That's it. Your commits should now be properly linted and prettified!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment