File: get-started.md

package info (click to toggle)
node-husky 9.1.7-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 952 kB
  • sloc: sh: 182; javascript: 79; makefile: 9
file content (80 lines) | stat: -rw-r--r-- 1,809 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# Get started

## Install

::: code-group

```shell [npm]
npm install --save-dev husky
```

```shell [pnpm]
pnpm add --save-dev husky
```

```shell [yarn]
yarn add --dev husky
# Add pinst ONLY if your package is not private
yarn add --dev pinst
```

```shell [bun]
bun add --dev husky
```

:::

## `husky init` (recommended)

The `init` command simplifies setting up husky in a project. It creates a `pre-commit` script in `.husky/` and updates the `prepare` script in `package.json`. Modifications can be made later to suit your workflow.

::: code-group

```shell [npm]
npx husky init
```

```shell [pnpm]
pnpm exec husky init
```

```shell [yarn]
# Due to specific caveats and differences with other package managers,
# refer to the How To section.
```

```shell [bun]
bunx husky init
```

:::


## Try it

Congratulations! You've successfully set up your first Git hook with just one command 🎉. Let's test it:

```shell
git commit -m "Keep calm and commit"
# test script will run every time you commit
```

## A few words...

### Scripting

While most of the time, you'll just run a few `npm run` or `npx` commands in your hooks, you can also script them using POSIX shell for custom workflows.

For example, here's how you can lint your staged files on each commit with only two lines of shell code and no external dependency:

```shell
# .husky/pre-commit
prettier $(git diff --cached --name-only --diff-filter=ACMR | sed 's| |\\ |g') --write --ignore-unknown
git update-index --again
```

_This is a basic but working example, check [lint-staged](https://github.com/lint-staged/lint-staged) if you need more._

### Disabling hooks

Husky doesn't force Git hooks. It can be globally disabled (`HUSKY=0`) or be opt-in if wanted. See the [How To](how-to) section for manual setup and more information.