tsclernamonorepolint-staged

How to use lint-staged in a lerna monorepo to run the same command in all packages?


I have the following root package.json:

{
  "name": "project",
  "private": true,
  "workspaces": [
    "packages/*"
  ],
  "scripts": {
    "build": "lerna run build",
    "dev": "lerna run start --stream --parallel",
    "format": "yarn prettier --write",
    "prettier": "prettier --ignore-path .gitignore \"**/*.+(ts|tsx|json)\"",
    "test": "lerna run test --"
  },
  "husky": {
    "hooks": {
      "pre-commit": "yarn format && yarn test"
    }
  },
  "devDependencies": {
    "husky": "^4.2.5",
    "lerna": "^3.22.1",
    "prettier": "^2.0.5"
  }
}

The problem is that using this setup, I cannot commit when I am still working on files, to fix this I can make use of the lint-staged module, my question is, how can I set it up so that the commands I currently have still run but only on staged files without installing all the dependencies of the command in every project? The test command might also be a problem since it runs tsc --noEmit in every project, can I force that to only check staged files too?


Solution

  • There is an alternate solution to this, because as of right now, lint-staged does not play well with lerna commands for testing.

    The solution involves using git commands in the package.json to stash files that are untracked and not staged, perform the test, and then after the test reimplement the untracked and files that aren't staged.

    The is one exception with this method, is that git see the files changes being brought back as merge conflicts that will need to be manually merged.

    Here are the changes to make:

    File: ./package.json

    {
      "name": "project",
      "private": true,
      "workspaces": [
        "packages/*"
      ],
      "scripts": {
        "build": "lerna run build",
        "dev": "lerna run start --stream --parallel",
        "format": "yarn prettier --write",
        "prettier": "prettier --ignore-path .gitignore \"**/*.+(ts|tsx|json)\"",
        "test": "lerna run test",
        "test:staged": "git stash -k --include-untracked; yarn test; git stash apply;"
      },
      "lint-staged": {
        "packages/**/*.{ts,js,json,md}": [
          "prettier --write"
        ]
      },
      "husky": {
        "hooks": {
          "pre-commit": "yarn format && yarn test:staged"
        }
      },
      "devDependencies": {
        "husky": "^4.2.5",
        "lerna": "^3.22.1",
        "prettier": "^2.0.5"
      }
    }
    

    More specifically this line:

    {
       "test:staged": "git stash -k --include-untracked; yarn test; git stash apply;"
    }