• The Viable SaaS
  • Posts
  • How To Automate Code Quality Checks in Your SaaS Development

How To Automate Code Quality Checks in Your SaaS Development

Use Husky and Lint-Staged to enforce code quality standards automatically

In my previous post, I talked about how ESLint and Prettier can help you maintain consistent code formatting across your Next.js application.

To automate this process, you can run a linting script before the build stage of your application as part of a Continuous Integration (CI) pipeline. You can also run it before your changes are committed and pushed upstream.

Husky is a tool that makes managing Git hooks straightforward. Git hooks are scripts that run automatically before or after events such as commit and push. These hooks can be used to inspect the code before these events, ensuring that only quality code gets committed to your repository.

Lint-Staged works by running linters against staged Git files. This tool ensures that all your modifications pass quality checks before they can be committed.

When integrated with Husky, you can automatically lint your code and run tests right before you commit, ensuring that any errors are caught early in the development cycle.

By focusing on staged files only, Lint-Staged ensures that you're not wasting time checking unmodified files, speeding up the development process significantly.

Husky and Lint-Staged can also be customized to run a test suite in addition to linters, but that might be overkill for most people.

What’s certainly not overkill is having these coding standards in place from the start so that when you have more developers, they can easily adhere to the project’s code standards.

To integrate Husky and Lint-Staged in your Next.js project, follow these steps:

1). Install the necessary packages:

npm install --save-dev husky lint-staged

2). Set up Husky:

npx husky init

3). Set up the pre-commit hook:

echo "lint-staged" > .husky/pre-commit

4). Configure Lint-Staged: In your package.json file add an object called lint-staged :

lint-staged: {     
    "*/**/*.{js,jsx,ts,tsx}": [
        "prettier --write",
        "eslint --fix",
        "eslint"
    ],
    "*/**/*.{json,css,md}": [
        "prettier --write"
    ]
}

5). Commit changes: Commit changes to package.json and .husky .

6). Test your setup: Stage some file changes and try committing them. If there are any lint errors, the commit will be halted, prompting you to fix the issues.

From the steps above, you can see that ESLint and Prettier are pretty common to run in a pre-commit hook. You can do more than that and run a test framework like Jest or a commit linter like commitlint.

Reply

or to participate.