Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NextJS - Linter with lint-staged not working

Tags:

next.js

I've set up lint-staged and husky with NextJS. When we run yarn lint, it calls yarn next lint under the hood and it works. When we call yarn lint-staged, we receive an error:

✖ yarn lint:
> Couldn't find a `pages` directory. Please create one under the project root

The point is that pages directory exists under src and it should work. What is going on?

package.json:

{
  "scripts": {
    "lint": "next lint"
  },
  "lint-staged": {
    "src/**/*.{ts,tsx}": [
      "yarn lint"
    ]
  }
}
like image 967
Stephan882 Avatar asked Sep 01 '25 16:09

Stephan882


2 Answers

use "eslint" instead of "yarn lint" under lint-staged.

I believe next lint has some inherent configurations that aren't compatible with lint-staged.

"eslint" catches the intended error during pre-commits

package.json

{
  "scripts": {
    "lint": "next lint"
  },
  "lint-staged": {
    "src/**/*.{ts,tsx}": [
      "eslint"
    ]
  }
}
like image 160
Nelson Lee Avatar answered Sep 05 '25 14:09

Nelson Lee


As written in the nextjs docs, next lint requires configuration for lint-staged.

Instead of the configuration in package.json,

in the root folder create file: .lintstagedrc.js

const path = require('path')
     
const buildEslintCommand = (filenames) =>
  `next lint --file ${filenames
    .map((f) => path.relative(process.cwd(), f))
    .join(' --file ')}`
  
module.exports = {
  '*.{js,jsx,ts,tsx}': [buildEslintCommand],
}
like image 20
safasafa Avatar answered Sep 05 '25 12:09

safasafa