What Will Be Set Up
- Husky pre-commit hook
- lint-staged Run Prettier on all staged files
- Prettier config (if missing)
- typecheck and test scripts run in the pre-commit hook
Steps
1. Detect package manager
Check package-lock.json(npm)、pnpm-lock.yaml(pnpm)、yarn.lock(yarn)、bun.lockb(bun). Use the one that already exists. If unsure, default to npm.
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 the following content (Husky v9+ does not require a shebang):
npx lint-staged
npm run typecheck
npm run test
AdaptReplace npm with the detected package manager. If the repository's package.json does not have the 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 no Prettier config exists. 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 that it works correctly
8. Commit
Stage all changed/created files and commit with the message:Add pre-commit hooks (husky + lint-staged + prettier)
This will trigger the new pre-commit hook to run: a good smoke test to verify everything works.
Notes
- Husky v9+ does not require a shebang in the hook file
prettier --ignore-unknownskips files that Prettier cannot parse (such as images, etc.)- The pre-commit hook runs lint-staged first (fast, only processes staged files), then runs the full typecheck and test