What This Sets Up
- Husky pre-commit hook
- lint-staged Run Prettier on all staged files
- Prettier config (if missing)
- and typecheck scripts in the test pre-commit hook
Steps
1. Detect package manager
Check for package-lock.json(npm)、pnpm-lock.yaml(pnpm)、yarn.lock(yarn)、bun.lockb(bun). Use whichever exists. Default to npm if unsure.
2. Install dependencies
Install as devDependencies:
husky lint-staged prettier
3. Initialize Husky
npx husky init
This creates the .husky/ directory and adds prepare: "husky"。
4. Create .husky/pre-commit
Write this file (Husky v9+ does not need a shebang):
npx lint-staged
npm run typecheck
npm run test
Adapt: replace npm with the detected package manager. If the repository's package.json does not have typecheck or test scripts, omit the corresponding lines and inform the user.
5. Create .lintstagedrc
{
"*": "prettier --ignore-unknown --write"
}
6. Create .prettierrc(if missing)
Only create it if there is no Prettier config. Use the following defaults:
{
"useTabs": false,
"tabWidth": 2,
"printWidth": 80,
"singleQuote": false,
"trailingComma": "es5",
"semi": true,
"arrowParens": "always"
}
7. Verify
-
.husky/pre-commitexists and is executable -
.lintstagedrcexists - The
preparescript in package.json is"husky" -
prettierconfig exists - Run
npx lint-stagedto verify it works
8. Commit
Stage all changed/created files and commit with the message:Add pre-commit hooks (husky + lint-staged + prettier)
This will run through the new pre-commit hooks—a good smoke test to verify everything works.
Notes
- Husky v9+ does not need a shebang written in the hook file
prettier --ignore-unknownSkip files that Prettier cannot parse (images, etc.)- pre-commit first runs lint-staged (fast, staged files only), then runs the full type check and tests