What this configures
- Husky pre-commit hook
- lint-staged Run Prettier on all staged files
- Prettier config (if missing)
- in the pre-commit hook, typecheck and test scripts
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 when unclear.
2. Install dependencies
Install as devDependencies:
husky lint-staged prettier
3. Initialize Husky
npx husky init
This creates the .husky/ dir 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 repo's package.json has no typecheck or test script, omit the corresponding line 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 these 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" - prettier config exists
- run
npx lint-stagedto verify it works
8. Commit
Stage all changed/created files, and commit with message:Add pre-commit hooks (husky + lint-staged + prettier)
This goes through the new pre-commit hooks and is a good smoke test.
Notes
- Husky v9+ does not need shebangs in hook files
prettier --ignore-unknownskips files that Prettier cannot parse (images, etc.)- pre-commit first runs lint-staged (fast, only on staged files), then runs the full typecheck and tests