如何禁止Angular2+/TypeScript项目开发者禁用TSLint规则?
Great question—dealing with overzealous rule disabling is a common pain point when trying to maintain a consistent, clean codebase with Angular and TypeScript. Here are actionable steps to lock down TSLint so your team can't bypass rules via inline comments or VSCode quick fixes:
1. Block Inline Disable Comments via TSLint Configuration
The most direct way is to enable TSLint's built-in check for disable comments. Open your project's tslint.json file and add the disableComments flag at the top level (same level as rules):
{ "defaultSeverity": "error", "disableComments": true, // This blocks all /* tslint:disable */-style comments "extends": ["tslint:recommended", "tslint-angular"], "rules": { // Your existing rules here "typeof-compare": true } }
With this setting, any attempt to use // tslint:disable-next-line or /* tslint:disable */ will trigger a TSLint error instead of bypassing the rule. This forces your team to fix the underlying code issue rather than disabling the rule.
2. Disable VSCode's Quick Fix for Rule Disabling
VSCode's TSLint extension adds a convenient "Disable rule..." quick fix option that makes it easy to bypass rules with one click. To remove this option entirely, update your VSCode settings.json (open via Ctrl+, or Cmd+,):
{ "tslint.enableDisableRuleCommand": false }
This will hide the "Disable rule..." option from the VSCode quick fix menu, eliminating the temptation to use it casually.
3. Enforce Checks with Pre-Commit Hooks
Even with the above settings, it's good to add a safety net for code commits. Use tools like husky and lint-staged to run TSLint automatically before any code is committed. This ensures no code with rule-disabling comments makes it into your repo.
First, install the dependencies:
npm install husky lint-staged --save-dev
Then add this configuration to your package.json:
{ "husky": { "hooks": { "pre-commit": "lint-staged" } }, "lint-staged": { "*.ts": ["tslint --project .", "git add"] } }
Now, if someone tries to commit code with disabled rules, the pre-commit hook will fail and block the commit until the issue is fixed.
4. Team Agreements & Code Reviews
Technical tools are great, but clear team rules go a long way. Make sure your team understands why rules are in place—for example, typeof-compare prevents bugs from incorrect type checks. If someone truly has a valid reason to bypass a rule (rare cases), require them to document it in a comment and get approval via code review before merging.
内容的提问来源于stack exchange,提问作者Faly

