Search code examples
node.jspackage.jsonlernamonorepoyarn-workspaces

How to format / test before every push in a Node.js monorepo?


I am aware of several tools like husky, lint-staged and prettier, currently I have a monorepo that is using yarn workspaces and lerna, before every push using git I want prettier to format my code and run a test script, it does not matter if this happens in every project but it would be nice to only run those scripts in the projects that are changed ofcourse, my question is what tools can really help me with this and how do I set them up? Do I set them up for each project individually or can I setup something in my root package.json? It currently looks like

{
  "name": "orgname",
  "private": true,
  "workspaces": [
    "packages/*"
  ],
  "scripts": {
    "build": "lerna run build",
    "dev": "lerna run start --stream --parallel",
    "test": "lerna run test --"
  },
  "husky": {
    "hooks": {
      "pre-commit": "npm test"
    }
  },
  "prettier": {
    "semi": true,
    "singleQuote": true,
    "trailingComma": "es5"
  },
  "devDependencies": {
    "lerna": "^3.22.1"
  }
}


Solution

  • You can add lint: ... script inside package.json of every lerna packages, for example;

    ./packages/web/package.json

     ...
      "scripts": {
       "lint": "vue-cli-service lint --fix"
      },
    

    ./packages/api/package.json

     ...
      "scripts": {
       "lint": "eslint --fix src",
      }
    

    and in the main package.json you can add a lint script that runs every lint command of packages.

    Lastly add it to the husky pre-commit hook, so it will run every time before you commit.

    ./package.json

     "scripts": {
       "lint": "lerna run lint"
      },
      "husky": {
        "hooks": {
          "pre-commit": "yarn lint && yarn test"
        }
      }