Skip to content

Commit

Permalink
chore(blog): update a blog
Browse files Browse the repository at this point in the history
  • Loading branch information
rxtsel committed Oct 23, 2024
1 parent 8eb0b45 commit 468b1ff
Show file tree
Hide file tree
Showing 2 changed files with 101 additions and 39 deletions.
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
---
title: 'How to Install Husky and Commitlint in Your Projects: A Step-by-Step Guide'
title: 'How to Install Husky, Commitlint, and lint-staged in Your Projects: A Step-by-Step Guide'
draft: false
description: 'Learn how to enhance commit quality and consistency in your software projects with Husky and Commitlint. This guide provides step-by-step instructions on installing and configuring these powerful tools, ensuring better collaboration and code maintenance through standardized commit messages.'
description: 'Learn how to improve the quality and consistency of your commits in software projects with Husky and Commitlint. This guide provides step-by-step instructions on how to install and configure these powerful tools, ensuring better collaboration and code maintenance through standardized commit messages.'
pubDate: '2024-02-07T18:40:10.762Z'
cover: ''
categories: ['Commits', 'Linter']
Expand All @@ -22,11 +22,11 @@ lang: en

## Introduction

**Husky** and **Commitlint** are powerful tools that can enhance the quality and consistency of your commits in software development projects. [Husky](https://typicode.github.io/husky/) allows you to set up [Git Hooks](#what-is-a-git-hook) in your Git repository, while [Commitlint](https://commitlint.js.org/#/) helps enforce consistent commit message conventions ([Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/)). In this step-by-step guide, you will learn how to install and configure Husky and Commitlint in your projects.
**Husky** and **Commitlint** are powerful tools that can improve the quality and consistency of your commits in software development projects. [Husky](https://typicode.github.io/husky/) allows you to configure [Git Hooks](#what-is-a-git-hook) in your Git repository, while [Commitlint](https://commitlint.js.org/#/) helps enforce consistent commit message conventions. ([Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/)). In this step-by-step guide, you'll learn how to install and configure Husky and Commitlint in your projects.

### Why Husky and Commitlint?

Have you ever experienced uploading changes to your repository and the CI performs an automatic deployment, but something goes wrong? When you check the logs, you realize that sometimes it's as simple as an indentation error. Well, with Husky, you can avoid these issues by running the linter before each commit. This way, you prevent changes with errors from being pushed and also ensure that such commits are not recorded in the history.
Have you ever pushed changes to your repository and the CI automatically deploys, but something goes wrong? When you check the logs, you realize it's something as simple as an indentation error. With Husky, you can prevent these issues by running the linter before each commit. This way, you avoid committing changes with errors, and also prevent that commit from being recorded in the history.

![image](/blog/how-to-install-husky-and-commitlint-in-your-projects-a-step-by-step-guide/indent-problem.webp)

Expand All @@ -40,41 +40,44 @@ Have you ever experienced uploading changes to your repository and the CI perfor

## What is a Git Hook?

A "Git Hook" is a custom script that you can trigger in response to specific events during the Git process. These events could be actions such as committing changes, pushing, merging branches, among others. Hooks allow you to execute scripts or perform actions automatically before or after these events occur in Git.
A "Git Hook" is a custom script that can be triggered in response to specific events during the Git process. These events can include actions such as committing, pushing, merging branches, among others. Hooks allow you to run scripts or perform actions automatically before or after these events occur in Git.

Git offers a series of predefined hooks, which you can adapt to fit your workflow needs. Some of the most common hooks include:
Git provides a set of predefined hooks, which you can adapt to your workflow needs. Some common hooks are:

- **pre-commit**: Executes before committing changes. You can use it to perform tasks such as running automated tests or checking code quality.
- **pre-commit**: Runs before committing changes. You can use it to run tasks such as automated tests or code quality checks.

- **pre-push**: Executes before pushing changes to the remote repository. It can be used to perform additional checks before sending changes to the server.
- **pre-push**: Runs before pushing changes to the remote repository. It can be used to perform additional checks before sending changes to the server.

- **post-commit**: Executes after a change has been committed. It can be used to perform additional tasks after a commit has been made.
- **post-commit**: Runs after a change has been committed. It can be used to perform additional tasks after a commit has been made.

- **post-receive**: Executes in the remote repository after receiving new changes. It can be useful for performing actions on the server after changes have been pushed to the remote repository.
- **post-receive**: Runs on the remote repository after receiving new changes. It can be useful for performing actions on the server after changes have been pushed to the remote repository.

## Installation and Configuration of Husky and Commitlint
## Installing and Configuring Husky, Commitlint and lint-staged

### Step 1: Set up Git Project
### Step 1: Set Up the Git Project

If you haven't already set up a Git repository for your project, initialize it by running the following command in your terminal:
If you don't have a Git repository set up for your project yet, initialize it by running the following command in your terminal:

```bash
git init
```

### Step 2: Install Husky

> Note:
> I will use the `ppnpm` package manager in this example, but you can use `pnpm` or `yarn` according to your preferences.
Husky can be easily installed using any package manager. In your terminal, run the following command to install Husky as a development dependency in your project:

```shell
npx husky-init && npm i
pnpx husky-init && pnpm i
```

This will create a folder named `.husky` in the root of your project, which contains Husky's predefined hooks. Husky will also add a `prepare` script to your `package.json` file that will automatically run after your project dependencies are installed.
This will create a `.husky` folder at the root of your project, containing Husky's predefined hooks. Husky will also add a `prepare` script to your `package.json`, which will run automatically after your project dependencies are installed.

### Step 3: Configure Husky

Now, you need to add the scripts you want to run before committing. For example, you can have it run the `lint` script from your `package.json` to execute the linter before each commit and automatically fix errors. In this case, we'll use `eslint` as the linter.
Now, you need to add the scripts you want to run before committing. For example, you can run the `lint` script from your `package.json` to execute the linter before each commit and automatically fix any errors. In this case, we'll use `eslint` as the linter.

```json
"scripts": {
Expand All @@ -83,50 +86,78 @@ Now, you need to add the scripts you want to run before committing. For example,
}
```

Then, let's modify the `pre-commit` script in the `.husky/pre-commit` file to execute the `lint` script before each commit.
Then, modify the `pre-commit` script in the `.husky/pre-commit` file to run the `lint` script before each commit.

```diff title=".husky/pre-commit"
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"

- npm test
+ npm run lint
- pnpm test
+ pnpm run lint
```

- _Replace `npm` with the package manager you are using._
- _Replace `pnpm` with the package manager you are using._

> Note: You can add any script you want to run before each commit in the `.husky/pre-commit` file, such as running automated tests, checking code quality, etc.
> Note: you can add any script you want to run before each commit in the `.husky/pre-commit` file, such as running automated tests, checking code quality, etc.
### Step 4: Install Commitlint

Now that Husky is set up to run Commitlint before each commit, you need to install Commitlint in your project. You can do this by running the following command in your terminal:

```shell
npm i @commitlint/cli @commitlint/config-conventional -D
pnpm i @commitlint/cli @commitlint/config-conventional -DE
```

### Step 5: Configure Commitlint

After installing Commitlint, you need to configure it to use a set of rules.

Create a file named `commitlint.config.js` in the root of your project with the following command:
Create a file called `commitlint.config.js` in the root of your project with the following command:

```shell
echo "module.exports = {extends: ['@commitlint/config-conventional']}" > commitlint.config.js
echo "module.exports = { extends: ['@commitlint/config-conventional'] }" > commitlint.config.js
```

Create the script to make commitlint run with the following command:
Create the script to run commitlint with the following command:

```shell
node node_modules/husky/lib/bin add .husky/commit-msg 'npx --no -- commitlint --edit "$1"'
```

## Ready to Commit!
Congratulations! You have successfully configured Husky and Commitlint in your project. Now, whenever you make a commit in your Git repository, Husky will run Commitlint to ensure your commit message follows the defined conventions.

## lint-staged (Optional)

If you want to run the linter only on modified files before each commit, you can install `lint-staged` and configure it in your project.

1. Install `lint-staged`:

```shell
pnpm i lint-staged -DE
```

2. Create a `.lintstagedrc` file in the root of your project and add the desired configuration. For example, to run `eslint` on modified `{js,jsx,ts,tsx}` files:

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

3. Add the script to `.husky/pre-commit` to run `lint-staged` before each commit:

```diff title=".husky/pre-commit"
#!/usr/bin/env sh
. "$(dirname -- "$0")/\_/husky.sh"
pnpm run lint
+ pnpx lint-staged
```

Congratulations! You have successfully set up Husky and Commitlint in your project. Now, every time you make a commit to your Git repository, Husky will run Commitlint to ensure that your commit message complies with the defined conventions.
Now, `lint-staged` will run the linter only on modified files before each commit.

## Conclusion

In this guide, you have learned how to install and configure Husky and Commitlint in your software development projects. By following these instructions, you can improve the quality and consistency of commit messages in your Git repository, making collaboration and code maintenance easier over time.
In this guide, you've learned how to install and configure Husky and Commitlint in your software development projects. By following these instructions, you can improve the quality and consistency of commit messages in your Git repository, making collaboration and code maintenance easier over time.
Now you are ready to start committing with confidence!
Now you're ready to start committing with confidence!
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
---
title: 'Cómo Instalar Husky y Commitlint en tus Proyectos: Una Guía Paso a Paso'
title: 'Cómo Instalar Husky, Commitlint y lint-staged en tus Proyectos: Una Guía Paso a Paso'
draft: false
description: 'Aprende cómo mejorar la calidad y consistencia de tus commits en proyectos de software con Husky y Commitlint. Esta guía proporciona instrucciones paso a paso sobre cómo instalar y configurar estas poderosas herramientas, asegurando una mejor colaboración y mantenimiento del código a través de mensajes de commit estandarizados.'
pubDate: '2024-02-07T18:40:10.762Z'
Expand Down Expand Up @@ -52,7 +52,7 @@ Git ofrece una serie de ganchos predefinidos, los cuales puedes adaptar según l

- **post-receive**: Se ejecuta en el repositorio remoto después de recibir nuevos cambios. Puede ser útil para realizar acciones en el servidor después de que se hayan empujado cambios al repositorio remoto.

## Instalación y Configuración de Husky y Commitlint
## Instalación y Configuración de Husky, Commitlint y lint-staged

### Paso 1: Configurar el Proyecto de Git

Expand All @@ -64,10 +64,13 @@ git init

### Paso 2: Instalar Husky

> Nota:
> Yo usare el gestor de paquetes `ppnpm` en este ejemplo, pero tú puedes usar `pnpm` o `yarn` según tus preferencias.
Husky se puede instalar fácilmente usando cualquier gestor de paquetes. En tu terminal, ejecuta el siguiente comando para instalar Husky como una dependencia de desarrollo en tu proyecto:

```shell
npx husky-init && npm i
pnpx husky-init && pnpm i
```

Esto te creará una carpeta llamada `.husky` en la raíz de tu proyecto, que contiene los ganchos predefinidos de Husky. Husky también añadirá un script `prepare` a tu archivo `package.json` que se ejecutará automáticamente después de que se instalen las dependencias de tu proyecto.
Expand All @@ -90,11 +93,11 @@ Entonces, vamos a modificar el script `pre-commit` en el archivo `.husky/pre-com
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"

- npm test
+ npm run lint
- pnpm test
+ pnpm run lint
```

- _Reemplaza `npm` por el gestor de paquetes que estés utilizando._
- _Reemplaza `pnpm` por el gestor de paquetes que estés utilizando._

> Nota: puedes agregar cualquier script que desees ejecutar antes de cada commit en el archivo `.husky/pre-commit`, como ejecutar pruebas automáticas, comprobar la calidad del código, etc.
Expand All @@ -103,7 +106,7 @@ Entonces, vamos a modificar el script `pre-commit` en el archivo `.husky/pre-com
Ahora que Husky está configurado para ejecutar Commitlint antes de cada commit, necesitas instalar Commitlint en tu proyecto. Puedes hacerlo ejecutando el siguiente comando en tu terminal:

```shell
npm i @commitlint/cli @commitlint/config-conventional -D
pnpm i @commitlint/cli @commitlint/config-conventional -DE
```

### Paso 5: Configurar Commitlint
Expand All @@ -113,7 +116,7 @@ Después de instalar Commitlint, necesitas configurarlo para que utilice un conj
Creamos un archivo llamado `commitlint.config.js` en la raíz de tu proyecto con el siguiente comando:

```shell
echo "module.exports = {extends: ['@commitlint/config-conventional']}" > commitlint.config.js
echo "module.exports = { extends: ['@commitlint/config-conventional'] }" > commitlint.config.js
```

Creamos el script para que se ejecute commitlint con el siguiente comando:
Expand All @@ -122,10 +125,38 @@ Creamos el script para que se ejecute commitlint con el siguiente comando:
node node_modules/husky/lib/bin add .husky/commit-msg 'npx --no -- commitlint --edit "$1"'
```

## ¡Listo para Commitear!

¡Felicidades! Has configurado con éxito Husky y Commitlint en tu proyecto. Ahora, cada vez que realices un commit en tu repositorio de Git, Husky ejecutará Commitlint para asegurarse de que tu mensaje de commit cumpla con las convenciones definidas.

## lint-staged

Si deseas ejecutar el linter solo en los archivos que han sido modificados antes de cada commit, puedes instalar `lint-staged` y configurarlo en tu proyecto.

1. Instalar `lint-staged`:

```shell
pnpm i lint-staged -DE
```

2. Crear un archivo `.lintstagedrc` en la raíz de tu proyecto y agregar la configuración deseada. Por ejemplo, para ejecutar `eslint` en los archivos `{js,jsx,ts,tsx}` modificados:

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

3. Agregar el script a `.husky/pre-commit` para ejecutar `lint-staged` antes de cada commit:

```diff title=".husky/pre-commit"
#!/usr/bin/env sh
. "$(dirname -- "$0")/\_/husky.sh"
pnpm run lint
+ pnpx lint-staged
```

Listo, ahora `lint-staged` ejecutará el linter solo en los archivos modificados antes de cada commit.

## Conclusion

En esta guía, has aprendido cómo instalar y configurar Husky y Commitlint en tus proyectos de desarrollo de software. Al seguir estas instrucciones, puedes mejorar la calidad y consistencia de los mensajes de commit en tu repositorio de Git, lo que facilita la colaboración y el mantenimiento del código a lo largo del tiempo.
Expand Down

0 comments on commit 468b1ff

Please sign in to comment.