Blog>
Snippets

Integrating ESLint with pre-commit hooks using Husky

Exhibit the setup required to run ESLint checks as pre-commit hooks using Husky in a Next.js project to ensure code quality before commits.
// Step 1: Install Husky

// Install Husky as a devDependency
npm install husky --save-dev
Install Husky using npm to add it as a dev dependency for your Next.js project.
// Step 2: Enable Git Hooks

// Enable Git hooks with husky by modifying package.json
npx husky install
Run the command to enable Git hooks using Husky by adding it to your package.json. This will create a .husky/ directory with a pre-commit file.
// Step 3: Add Husky Pre-commit Hook

// In package.json, add a 'prepare' script
"scripts": {
  "prepare": "husky install"
}
Add a 'prepare' script to your package.json to ensure Husky is installed whenever 'npm install' is run.
// Step 4: Configure Pre-commit Hook

// Add pre-commit hook that will run ESLint
npx husky add .husky/pre-commit "npm run lint"
Using Husky, add a pre-commit hook by creating a pre-commit file inside the .husky directory. This hook will call 'npm run lint' which should be defined in your package.json to run ESLint.
// Step 5: Configure ESLint Script

// In package.json, add the lint script
"scripts": {
  "lint": "next lint"
}
Add a 'lint' script in your package.json which will be used by the pre-commit hook to run ESLint checks using Next.js built-in ESLint configuration.
// Step 6: Install ESLint

// Install ESLint if it is not already a part of the project
npm install eslint --save-dev
If ESLint is not already installed, add it to your project as a dev dependency using npm.