JS生态下Husky用户如何在CI服务器检查PR代码质量?
Great question! While Husky + lint-staged is optimized for local pre-commit checks on staged files, there are straightforward ways to replicate the "check all files" (or targeted PR changes) behavior in your CI pipeline. Here are the most common, practical approaches:
1. Run Linters/Formatters Directly on the Entire Codebase
The simplest method is to execute the same linting/formatting commands you use locally, but apply them to every file in the repo instead of just staged ones. This ensures the entire codebase adheres to your standards, which is perfect for enforcing PR quality.
For example:
- If you use ESLint:
eslint . --max-warnings 0 - If you use Prettier:
prettier --check . - For TypeScript:
tsc --noEmit
Add these commands to your CI workflow file (like GitHub Actions, GitLab CI, etc.). If any command exits with a non-zero code (i.e., finds errors/warnings), the CI build will fail, blocking the PR from being merged.
2. Target Only Files Changed in the PR
For larger codebases, checking every file can be slow. Instead, you can run checks only on the files modified in the PR to speed up the CI process.
First, get the list of changed files using git:
# Compare your PR branch with the default branch (e.g., main) CHANGED_FILES=$(git diff --name-only origin/main...HEAD)
Then, pass these files to your linters. For example, with ESLint:
# Filter for JS/TS files and run ESLint (use --no-run-if-empty to avoid errors if no files match) echo "$CHANGED_FILES" | grep -E '\.(js|ts|jsx|tsx)$' | xargs --no-run-if-empty eslint --max-warnings 0
3. Use lint-staged with Custom File Globs
Did you know lint-staged itself supports running checks on arbitrary files (not just staged ones)? Use the --files flag to specify a glob pattern matching all files, which acts as the direct equivalent of pre-commit run --all-files.
For example:
# Run your existing lint-staged config on all files in the repo lint-staged --files "**/*"
This uses your existing lint-staged configuration (from package.json or .lintstagedrc) and applies it to every file. It’s a great way to keep your CI checks aligned with your local pre-commit hooks without duplicating configuration.
Key Tips for CI Setup
- Skip auto-fixes in CI: You don’t want CI modifying files (since those changes won’t be committed). Use check-only modes like
prettier --checkoreslintwithout the--fixflag. - Cache dependencies: Speed up CI runs by caching
node_modulesand linter caches (e.g., ESLint’s cache) to avoid reinstalling and rechecking from scratch every time. - Align versions: Ensure the versions of Husky, lint-staged, and your linters in CI match what’s used locally (use
package-lock.jsonoryarn.lockto enforce this).
Content of the question originates from stack exchange, question author Migwell




