๐Ÿ‘ฎEnforcing Coding Conventions

Ensuring code quality is very important for a maintainable and scalable application. As a default, this generator automatically will install and configure ESLint and Prettier in your project, for a consistent code formatting. ( Read more about this in Code formatting section. ).

To help you enforce this standards, the generator also comes with this great library called Husky ( ๐Ÿถ woof! ).

Husky is a JavaScript package that allows you to run some code during various parts of your git workflow. Husky leverages git hooks to allow you to hook into various git events such as pre-commit and pre-push.

This application uses husky to trigger lint-staged during the pre-commit hook to automate the tedious part of your workflows, such as formatting with Prettier and/or linting with ESLint. Your code gets fixed before it ever leaves your machine, so you donโ€™t have to wait for your CI to inform you that you forgot to run the formatter or linter.

Configuring a monorepo with multiple packages

By design, husky install must be run in the same directory as .git.

If your project is a monorepo containing multiple packages, for example a Server and Client sub-folders, husky will expects your package.json to be at the root of your project.

If you don't want to add a separate package.json in your root just for this, you need to change the husky configurations in your Server and Client projects as follows:

  • Change directory during prepare script and pass a subdirectory

    // clientProject/package.json
    "scripts": {
      "prepare": "cd .. && husky install clientProject/.husky"
    }
    // serverProject/package.json
    "scripts": {
      "prepare": "cd .. && husky install serverProject/.husky"
    }
  • You'll also need to change directory in one of Client or Server hooks and write for both projects

    // clientProject/.husky/pre-commit
    #!/bin/sh
    . "$(dirname "$0")/_/husky.sh"
    cd serverProject
    npx lint-staged
    npm run test:ci
    cd ../clientProject
    npx lint-staged
    npm run test:ci
  • Run npm install in both projects and thatโ€™s it! Now if you try to make a commit, you will see that eslint and prettier will run and fix themselves as you would expect.

Last updated