user13103906
user13103906

Reputation:

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"
  }
}

Upvotes: 2

Views: 4547

Answers (2)

Luís Brito
Luís Brito

Reputation: 1772

Added a comment to the selected answer about using the lint-staged package, basically it enables you to apply linting and other routines specifically to changed files, and not all the package. It may be useful, depending on how you're using the monorepo approach.

/packages/example-name/.lintstagedrc.json

{
  "*.{js,ts}": ["eslint --fix", "git add"]
}

/packages/example-name/package.json

{
  [...]

  "scripts": {
    "precommit": "lint-staged"
  }

  [...]
}

/package.json

{
  [...]

  "husky": {
    "hooks": {
      "pre-commit": "lerna run precommit --since HEAD"
    }
  },

  [...]
}

For more information: https://github.com/okonet/lint-staged

Upvotes: 1

onuriltan
onuriltan

Reputation: 3908

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"
    }
  }

Upvotes: 2

Related Questions