0
# Husky
1
2
Husky is a modern native Git hooks tool that provides ultra-fast and lightweight Git hook management for automatically enforcing code quality, commit standards, and running development checks. With around 1ms execution time and only 2kB package size, it offers all 14 client-side Git hooks with exceptional performance and minimal overhead.
3
4
## Package Information
5
6
- **Package Name**: husky
7
- **Package Type**: npm
8
- **Language**: JavaScript (ES Modules)
9
- **Installation**: `npm install husky --save-dev`
10
- **Requirements**: Node.js >= 18, Git
11
12
## Core Imports
13
14
```javascript
15
import husky from "husky";
16
```
17
18
For CommonJS:
19
```javascript
20
const husky = require("husky");
21
```
22
23
## Basic Usage
24
25
```javascript
26
// Initialize husky in your project
27
import husky from "husky";
28
29
// Set up hooks with default directory
30
const result = husky();
31
console.log(result); // "" on success or error message
32
33
// Set up hooks with custom directory
34
const result = husky('.git-hooks');
35
console.log(result); // "" on success or error message
36
```
37
38
CLI usage:
39
```bash
40
# Initialize husky in project
41
npx husky init
42
43
# Install hooks (legacy command, shows deprecation warning)
44
npx husky install
45
46
# Install hooks with custom directory
47
npx husky .custom-hooks
48
```
49
50
## Capabilities
51
52
### Installation and Setup
53
54
Core installation function that configures Git hooks and creates the necessary directory structure.
55
56
```javascript { .api }
57
/**
58
* Install and configure husky Git hooks
59
* @param dir - Target directory for husky installation (default: '.husky')
60
* @returns Status message - empty string on success, error message on failure
61
*/
62
function husky(dir?: string): string;
63
```
64
65
**Installation Process:**
66
- Validates directory path (rejects paths containing '..')
67
- Checks for Git repository (.git directory must exist)
68
- Configures Git's core.hooksPath to point to husky directory
69
- Creates hook directory structure with appropriate permissions
70
- Generates executable hook scripts for all supported Git hooks (with 0o755 permissions)
71
- Sets up shell script runner (husky executable) and configuration files
72
- Creates .gitignore file in hooks directory to ignore all hook contents
73
74
**Environment Variables:**
75
- `HUSKY=0` - Completely skips installation when set
76
- `HUSKY=2` - Enables debug mode for hook execution
77
78
**Error Handling:**
79
```javascript
80
const result = husky();
81
if (result) {
82
console.error('Husky installation failed:', result);
83
// Possible error messages:
84
// "HUSKY=0 skip install"
85
// ".. not allowed"
86
// ".git can't be found"
87
// "git command not found"
88
// Git configuration errors
89
}
90
```
91
92
### CLI Commands
93
94
Command-line interface for project initialization and hook management.
95
96
```bash { .api }
97
# Initialize husky in project (recommended)
98
npx husky init
99
100
# Install hooks with default directory
101
npx husky
102
# Alternative: npx husky install (shows deprecation warning)
103
104
# Install hooks with custom directory
105
npx husky <directory>
106
```
107
108
**`husky init` Command:**
109
- Reads and modifies package.json, preserving original formatting (tabs vs spaces)
110
- Adds `"prepare": "husky"` script to package.json scripts section
111
- Creates `.husky` directory
112
- Generates default `.husky/pre-commit` hook with package manager-specific test command
113
- Automatically detects package manager from npm_config_user_agent environment variable
114
- Default pre-commit content: `<detected_package_manager> test\n` (e.g., "npm test", "pnpm test", "yarn test")
115
- Calls main installation function
116
- Process exits immediately after completion
117
118
**Deprecated Commands:**
119
- `husky add` - Shows deprecation warning and exits with code 1
120
- `husky set` - Shows deprecation warning and exits with code 1
121
- `husky uninstall` - Shows deprecation warning and exits with code 1
122
- `husky install` - Shows deprecation warning but continues execution (legacy compatibility)
123
124
### Git Hook Support
125
126
Husky supports all 14 client-side Git hooks with automatic script generation.
127
128
```javascript { .api }
129
// Supported Git hooks (automatically created):
130
const SUPPORTED_HOOKS: readonly string[] = [
131
'pre-commit',
132
'pre-merge-commit',
133
'prepare-commit-msg',
134
'commit-msg',
135
'post-commit',
136
'applypatch-msg',
137
'pre-applypatch',
138
'post-applypatch',
139
'pre-rebase',
140
'post-rewrite',
141
'post-checkout',
142
'post-merge',
143
'pre-push',
144
'pre-auto-gc'
145
];
146
```
147
148
**Hook Script Structure:**
149
Each generated hook script:
150
- Points to husky's shell runner executable
151
- Executes user-defined commands from corresponding hook files
152
- Provides error reporting with exit codes
153
- Supports PATH modification for node_modules/.bin access
154
155
### Runtime Configuration
156
157
Runtime behavior and configuration options for hook execution.
158
159
```bash { .api }
160
# Environment variables for hook execution:
161
export HUSKY=0 # Disable all hook execution
162
export HUSKY=2 # Enable debug mode (shows detailed execution)
163
164
# User configuration file (optional):
165
~/.config/husky/init.sh # Global initialization script
166
```
167
168
**User Configuration:**
169
- Place global configuration in `~/.config/husky/init.sh`
170
- Deprecated `~/.huskyrc` still supported with warning
171
- Configuration runs before each hook execution
172
- Can modify environment, PATH, or add global setup
173
174
**Runtime Features:**
175
- Automatic PATH modification to include `node_modules/.bin`
176
- Graceful handling of missing hook scripts
177
- Detailed error reporting with exit codes
178
- Cross-platform compatibility (macOS, Linux, Windows)
179
180
## Installation Workflow
181
182
**Automatic Setup (Recommended):**
183
```bash
184
npm install husky --save-dev
185
npx husky init
186
```
187
188
**Manual Setup:**
189
```javascript
190
import husky from "husky";
191
192
// Install hooks
193
const result = husky();
194
if (result) {
195
throw new Error(`Husky setup failed: ${result}`);
196
}
197
198
// Create custom hooks
199
import fs from 'fs';
200
fs.writeFileSync('.husky/pre-commit', 'npm test\n', { mode: 0o755 });
201
fs.writeFileSync('.husky/commit-msg', 'npx commitlint --edit $1\n', { mode: 0o755 });
202
```
203
204
## Types
205
206
```typescript { .api }
207
/**
208
* Main husky installation function
209
*/
210
declare function husky(dir?: string): string;
211
212
export default husky;
213
```