Search code examples
eslintprettierlint-staged

How to configure lint-staged to run eslint and prettier scripts


I have this setup:

// package.json

...
  "scripts": {
    ...
    "lint": "eslint --fix {src,test}/**/*.{js,ts,jsx,tsx} --no-error-on-unmatched-pattern",
    "style": "prettier --write {src,test}/**/* ./*.{json,*.json} !package-lock.json -u --no-error-on-unmatched-pattern",
...
  "lint-staged": {
    "lint-staged": {
      "{src,test}/**/*.{js,ts,jsx,tsx}": [
        "npm run lint",
        "npm run style"
      ],
      "!**/*.{js,ts,jsx,tsx}": "npm run style"
    },
  }
...

The problem is that prettier will run no matter what file is matched by the glob, prettier will also double run on all files and rewrite all of them twice.


Solution

  • You can't use double glob expressions when using lint-staged, it will cause conflicts.

    // package.json
    
    ...
      "scripts": {
        ...
        "lint": "eslint --fix {src,test}/**/*.{js,ts,jsx,tsx} --no-error-on-unmatched-pattern",
        "style": "prettier --write {src,test}/**/* ./*.{json,*.json} !package-lock.json -u --no-error-on-unmatched-pattern",
    ...
      "lint-staged": {
        "lint-staged": {
          "{src,test}/**/*.{js,ts,jsx,tsx}": [
            "eslint --fix",
            "prettier --write -u"
          ],
          "!**/*.{js,ts,jsx,tsx}": "prettier --write -u"
        },
      }
    ...
    

    Just use prettier --write -u and eslint --fix when you're running lint-staged, don't run your custom scripts otherwise the globs with conflict with one another. Instead just run eslint and prettier directly on the glob matched by lint-staged.