Write precommit hooks for NextJS project with pre-commit

2 min read

We have already seen an example of how to write a pre-commit hook configuration. If you haven’t see my previous article, then please refere to my last post.

Now, let's explore how to configure it for our NextJS project. Firstly, let's take another look at the sample configuration.

1repos: 2- repo: https://github.com/pre-commit/mirrors-eslint 3 rev: v7.0.0 4 hooks: 5 - id: eslint 6   name: eslint 7   entry: npx 8   args: [eslint, --fix, .] 9   language: node 10   types: [jsx] 11   exclude: "node_modules"

This is a pre-commit hook configuration that installs and runs the eslint linter on the specified files in a project.

The configuration specifies the repository URL of ESLint under the repos section. It also specifies which version to use.

The hook has the following properties:

  • id: The unique identifier of the hook, which is eslint in this case.
  • name: The human-readable name of the hook that would be displayed during run.
  • entry: The command to execute for this hook, which is npx in this case to run the locally installed eslint package.
  • args: The arguments to pass to the command when it's executed. In this case, the hook runs eslint --fix to automatically fixes any issues it finds. . specifies to lints all files in the current directory.
  • language: The language the hook is written in, which is node in this case.
  • types: A list of file types that this hook should be run on. In this case, the hook is run on JavaScript, TypeScript, JSX, TSX, and JSON files.
  • exclude: Here, you can specify to ignore any directories or files.

Remember, you can also specify your exclude files/folders in .eslintignore file as below. This will be in addition to above.

1out/ 2.vercel/ 3public/

It'll also pick up any rules specified under your .eslintrc.js file.

1rules: { 2    'max-len': [2, { code: 120 }], 3    'no-console': [2, { allow: ['warn', 'error'] }], 4    'no-unused-vars': 0, 5 },

Here, we're specifying various rules to guide our ESLint. For example, you can notice that we're specifying maximum line length to 120 characters maximum(max-len). Same way, we're discouraging console logs* exceptwarn or error.

We disabled unused variable errors here by specifying 0