@george2f/eslint-plugin-clean-code

中文文档
0.5.0发布于 2026/10/19MITTypeScriptESM + CJS零依赖构建来源已验证近 30 天下载 8928

ESLint rules derived from the book Clean Code (Robert C. Martin)

原始使用文档
文档目录22 节
  1. Why this exists
  2. Install
  3. Usage
  4. Configs
  5. Rule tiers
  6. Machine-readable rule catalog
  7. Chapter 17: Smells and Heuristics
  8. Comments
  9. Environment
  10. Functions
  11. General
  12. Java section
  13. Names
  14. Tests
  15. Chapter-derived rules
  16. Options
  17. Autofix and suggestions
  18. Overlap with core ESLint rules
  19. Heuristics
  20. Development
  21. Releasing
  22. License

eslint-plugin-clean-code

npm version CI license

ESLint rules derived from Clean Code by Robert C. Martin.

Every rule maps to a numbered book rule (Chapter 17 "Smells and Heuristics", plus selected rules from Chapters 3, 7 and 9), and every reference is kept in the rule metadata (meta.docs.cleanCodeId), so a lint report points straight back to the book.

  • 44 ESLint rules, one per book rule
  • Chapters 17's 66 numbered heuristics: 39 automated, 27 documented as not statically detectable (see Chapter 17 mapping)
  • ESLint 9 flat config, TypeScript-friendly, dual ESM/CJS build

Why this exists

I wrote this plugin because I always wondered how hard it would be to follow all of the Clean Code rules. It turns out it is hard for humans and trivial for agents — so now, instead of you following the rules, your agents follow them for you. Point them at strict, or strictest if you are feeling brave, and they will write clean, consistent, heavily rule-bound code that would make even the lousiest bot cry tears of consistent and clean joy.

Install

npm install --save-dev eslint @george2f/eslint-plugin-clean-code

Requires ESLint >= 8.57 (8.57, 9.x and 10.x are supported; zero runtime dependencies). The configs.recommended / configs.strict exports are flat-config objects; on legacy .eslintrc setups, register the plugin (plugins: ['@george2f/clean-code']) and enable rules manually.

Usage

// eslint.config.js
import cleanCode from '@george2f/eslint-plugin-clean-code';

export default [
  cleanCode.configs.recommended, // 12 high-confidence rules, all errors
  // cleanCode.configs.strict,     // all 44 rules; static = error, heuristic = warn
  // cleanCode.configs.strictest,  // all 44 rules at error, heuristics included
];

Or pick rules individually:

import cleanCode from '@george2f/eslint-plugin-clean-code';

export default [
  {
    plugins: { 'clean-code': cleanCode },
    rules: {
      'clean-code/max-arguments': ['error', { max: 4 }],
      'clean-code/law-of-demeter': ['warn', { maxChainLength: 2 }],
    },
  },
];

Configs

ConfigRulesSeverityIntent
clean-code/recommended12errorReliable AST detection, low false-positive rate
clean-code/strict44error static / warn heuristicEverything, including opinionated heuristics
clean-code/strictest44errorEverything as an error, heuristics included; expect to tune options

The 12 recommended rules: max-arguments, no-commented-out-code, no-dead-code, no-encodings, no-flag-arguments, no-magic-numbers, no-negative-conditionals, no-overridden-safeties, no-pass-null, no-return-null, no-skipped-tests, no-todo-tests.

Rule tiers

  • static — reliable AST detection; ships in recommended.
  • heuristic — threshold-based detection with configurable options; warn by default in strict and error in strictest. Expect to tune options or disable a few in real codebases; every heuristic has a documented option set (see Options).

Machine-readable rule catalog

The published package ships rules.json (importable as @george2f/eslint-plugin-clean-code/rules.json): every rule with its book ID, tier, config membership, default options, JSON schema, autofix/suggestion flags, and docs link. Useful for tooling and coding agents.

Chapter 17: Smells and Heuristics

Legend: static ships in recommended · heuristic ships in strict as warning · doc-only is intentionally not implemented (reason given) — no fake rules.

Comments

IDBook ruleRuleKind
C1Inappropriate Informationclean-code/no-inappropriate-commentsheuristic
C2Obsolete Comment—doc-only — requires semantic knowledge of what the code does
C3Redundant Commentclean-code/no-redundant-commentsheuristic
C4Poorly Written Comment—doc-only — subjective; review manually
C5Commented-Out Codeclean-code/no-commented-out-codestatic

Environment

IDBook ruleRuleKind
E1Build Requires More Than One Step—doc-only — keep one npm run build; build tooling, not lint
E2Tests Require More Than One Step—doc-only — keep one npm test; test tooling, not lint

Functions

IDBook ruleRuleKind
F1Too Many Argumentsclean-code/max-argumentsstatic
F2Output Argumentsclean-code/no-output-argumentsheuristic
F3Flag Argumentsclean-code/no-flag-argumentsstatic
F4Dead Functionclean-code/no-dead-functionsheuristic — same file only

General

IDBook ruleRuleKind
G1Multiple Languages in One Source Fileclean-code/no-multiple-languagesheuristic
G2Obvious Behavior Is Unimplemented—doc-only — requires intent; use TDD and review
G3Incorrect Behavior at the Boundaries—doc-only — boundary tests (T5), not lint
G4Overridden Safetiesclean-code/no-overridden-safetiesstatic
G5Duplicationclean-code/no-duplicationheuristic — same file; use jscpd for cross-file clones
G6Code at Wrong Level of Abstraction—doc-only — design judgement
G7Base Classes Depending on Their Derivativesclean-code/no-base-class-knowing-derivativesheuristic
G8Too Much Informationclean-code/limited-public-apiheuristic
G9Dead Codeclean-code/no-dead-codestatic
G10Vertical Separationclean-code/declaration-proximityheuristic
G11Inconsistency—doc-only — use Prettier and shared configs
G12Clutterclean-code/no-clutterheuristic
G13Artificial Coupling—doc-only — design judgement
G14Feature Envyclean-code/no-feature-envyheuristic
G15Selector Argumentsclean-code/no-selector-argumentsheuristic
G16Obscured Intentclean-code/no-obscured-intentheuristic
G17Misplaced Responsibility—doc-only — design judgement
G18Inappropriate Staticclean-code/no-inappropriate-staticsheuristic
G19Use Explanatory Variablesclean-code/use-explanatory-variablesheuristic
G20Function Names Should Say What They Doclean-code/function-names-say-what-they-doheuristic
G21Understand the Algorithm—doc-only — requires comprehension; review
G22Make Logical Dependencies Physical—doc-only — design judgement
G23Prefer Polymorphism to If/Else or Switch/Caseclean-code/prefer-polymorphismheuristic
G24Follow Standard Conventions—doc-only — encode conventions as lint rules instead
G25Replace Magic Numbers with Named Constantsclean-code/no-magic-numbersstatic
G26Be Preciseclean-code/be-preciseheuristic
G27Structure over Convention—doc-only — design judgement
G28Encapsulate Conditionalsclean-code/encapsulate-conditionalsheuristic
G29Avoid Negative Conditionalsclean-code/no-negative-conditionalsstatic
G30Functions Should Do One Thingclean-code/function-does-one-thingheuristic
G31Hidden Temporal Couplings—doc-only — requires runtime ordering knowledge
G32Don't Be Arbitrary—doc-only — style consistency; use shared configs
G33Encapsulate Boundary Conditionsclean-code/encapsulate-boundariesheuristic
G34Functions Should Descend Only One Level of Abstractionclean-code/one-level-of-abstractionheuristic
G35Keep Configurable Data at High Levels—doc-only — placement judgement
G36Avoid Transitive Navigation (Law of Demeter)clean-code/law-of-demeterheuristic

Java section

IDBook ruleRuleKind
J1Avoid Long Import Lists by Using Wildcardsclean-code/prefer-namespace-importsheuristic — fights tree-shaking; opt in deliberately
J2Don't Inherit Constantsclean-code/no-inherited-constantsheuristic
J3Constants versus Enums—doc-only — TypeScript idioms differ from Java

Names

IDBook ruleRuleKind
N1Choose Descriptive Namesclean-code/descriptive-namesheuristic
N2Choose Names at the Appropriate Level of Abstraction—doc-only — requires domain knowledge
N3Use Standard Nomenclature Where Possible—doc-only — needs a project lexicon
N4Unambiguous Namesclean-code/no-ambiguous-namesheuristic
N5Use Long Names for Long Scopesclean-code/long-names-for-long-scopesheuristic
N6Avoid Encodingsclean-code/no-encodingsstatic
N7Names Should Describe Side Effectsclean-code/names-describe-side-effectsheuristic

Tests

IDBook ruleRuleKind
T1Insufficient Tests—doc-only — use a coverage tool (c8, nyc)
T2Use a Coverage Tool!—doc-only — same
T3Don't Skip Trivial Testsclean-code/no-skipped-testsstatic
T4An Ignored Test Is a Question about an Ambiguityclean-code/no-todo-testsstatic
T5Test Boundary Conditions—doc-only — test design, not lint
T6Exhaustively Test Near Bugs—doc-only
T7Patterns of Failure Are Revealing—doc-only
T8Test Coverage Patterns Can Be Revealing—doc-only
T9Tests Should Be Fast—doc-only

Chapter-derived rules

Lintable rules from earlier chapters that are not in the Chapter 17 list:

ChapterPrincipleRuleKind
3Command-Query Separationclean-code/command-query-separationheuristic
3Prefer Exceptions to Returning Error Codesclean-code/prefer-exceptions-over-error-codesheuristic
7Don't Return Nullclean-code/no-return-nullstatic
7Don't Pass Nullclean-code/no-pass-nullstatic
9One Assert per Testclean-code/one-assertion-per-testheuristic

Chapter principles with no lintable rule (documented, by design): Boy Scout Rule, KISS, find the root cause, use dependency injection, separate multi-threading code, prevent over-configurability, prefer dedicated value objects to primitives, hide internal structure, prefer data structures, F.I.R.S.T. (partially covered by no-skipped-tests and one-assertion-per-test), and all formatting rules (use Prettier).

Options

Every rule accepts an options object; partial options are merged with the defaults shown below.

RuleDefaults
max-arguments{ max: 3 }
no-dead-code{ ignoreNames: [], ignoreRestSiblings: true }
no-magic-numbers{ ignore: [0, 1, 2, -1], ignoreDefaultValues: true, ignoreArrayIndexes: false, ignoreEnums: true }
no-pass-null{ ignoreCallees: ['^use[A-Z]'] }
no-return-null{ allowNullableReturnType: true }
no-skipped-tests{ testFunctions: ['it', 'test', 'describe', 'context', 'suite', 'specify'] }
no-todo-tests{ testFunctions: ['it', 'test', 'specify'] }
no-inappropriate-comments{ patterns: [] } (extra regex sources)
no-redundant-comments—
no-output-arguments—
no-dead-functions{ allow: [] }
function-does-one-thing{ maxStatements: 20, maxLines: 30 }
one-level-of-abstraction{ minLowLevelOps: 3, minHighLevelCalls: 2 }
no-multiple-languages{ checkSql: true, checkHtml: true }
no-duplication{ minStatements: 4, minNodes: 25 }
limited-public-api{ maxClassMembers: 25, maxExports: 50 }
declaration-proximity{ maxDistance: 15 }
no-feature-envy{ minimumAccesses: 4 }
no-selector-arguments{ minComparisons: 2 }
use-explanatory-variables{ minComplexLookups: 1 }
function-names-say-what-they-do{ forbidden: ['handle', 'process', 'manage', 'util', 'utils', 'misc', 'stuff', 'thing', 'data', 'info', 'temp', 'tmp', 'foo', 'bar', 'baz', 'func', 'fn', 'callback', 'cb', 'do', 'perform', 'execute', 'handleData', 'doStuff', 'doWork', 'doIt'] }
prefer-polymorphism{ maxSwitchCases: 4, maxIfElseBranches: 5 }
encapsulate-conditionals{ maxLogicalOperators: 2 }
law-of-demeter{ maxChainLength: 3, allow: [] }
descriptive-names{ allow: ['i', 'j', 'k', 'x', 'y', 'z', 'e', '_'], forbidden: ['data', 'info', 'stuff', 'thing', 'temp', 'tmp', 'foo', 'bar', 'baz', 'obj', 'arr', 'val', 'utils', 'misc'] }
no-ambiguous-names{ confusingNames: ['l', 'O', 'I'] }
long-names-for-long-scopes{ minLength: 3, allow: ['i', 'j', 'k', 'x', 'y', 'z', 'e', '_', 'it'] }
no-encodings{ patterns: [], typePrefixes: false }
names-describe-side-effects{ prefixes: ['get', 'is', 'has', 'find'] }
prefer-namespace-imports{ maxNamedImports: 10 }
one-assertion-per-test{ maxAssertions: 1, testFunctions: ['it', 'test'] }
no-overridden-safeties{ allowEmptyCatch: false, allowTsIgnore: false, requireDisableReason: true }

Rules not listed above take no options.

max-arguments counts each binding in a destructuring pattern individually, recursing into nested patterns; a rest binding counts as one. function f({ a, b, c, d }) therefore has four arguments.

Autofix and suggestions

Three rules support eslint --fix:

RuleAutomatic fix
no-negative-conditionals (G29)Swaps the branches and removes the ! (consecutive negations like !! are removed in one pass)
no-clutter (G12)Removes stray ; statements, turns empty control-flow bodies into {}, deletes useless constructors
no-dead-code (G9, imports only)Removes the unused import specifier and rewrites the declaration (or emits import "mod"; when nothing remains, preserving module side effects)

Editor quick-fixes (suggestions — applied per occurrence, never by --fix):

RuleSuggestion
C5 / C1 / C3 comment rulesDelete the comment
no-dead-code (G9)Remove an unused variable declaration (only when its initializer has no side effects), or remove the unreachable statement
no-dead-functions (F4)Delete the dead function or private method
no-skipped-tests (T3)Un-skip the test
no-clutter (G12)Remove the debugger statement
no-overridden-safeties (G4)Replace @ts-ignore with @ts-expect-error

Overlap with core ESLint rules

Some rules intentionally re-implement book semantics that overlap with core or other popular rules. Enable only one side to avoid duplicate reports:

This pluginOverlaps with
max-arguments (F1)core max-params
no-magic-numbers (G25)core no-magic-numbers
no-negative-conditionals (G29)core no-negated-condition
no-dead-code (G9)core no-unused-vars, no-unreachable, @typescript-eslint/no-unused-vars
no-obscured-intent (G16)core no-nested-ternary, no-sequences, no-cond-assign
no-skipped-tests (T3)jest/no-disabled-tests, vitest/no-disabled-tests
no-overridden-safeties (G4)@typescript-eslint/ban-ts-comment (for @ts-ignore)

Heuristics

Heuristic rules are approximations of judgement calls. Every threshold is an option; if a heuristic is noisy in your codebase, first tune its options, then disable it with a comment that explains why — which is exactly the kind of comment the book approves of.

Development

npm install
npm test            # vitest + ESLint RuleTester (44 rule suites + integration test)
npm run typecheck   # tsc --noEmit
npm run build       # tsup -> dist (minified ESM + CJS + d.ts + rules.json)
npm run verify:dist # checks the built bundles (rule count, configs, meta)
npm run lint        # builds, then lints the plugin with its own rules + typescript-eslint

Each rule lives in src/rules/<rule-name>.ts with a colocated .test.ts. The book reference is in meta.docs.cleanCodeId and meta.docs.cleanCodeRule. Contributor notes for coding agents live in AGENTS.md.

Releasing

Published from CI with npm trusted publishing (OIDC); no tokens are stored anywhere.

  1. Bump version in package.json and add a changelog entry
  2. Commit, then tag and push: git tag vX.Y.Z && git push origin vX.Y.Z
  3. .github/workflows/release.yml lints, tests, creates a GitHub Release from the matching changelog section, and publishes with provenance

One-time setup: on npmjs.com, configure the package's trusted publisher as GitHub Actions, repository George2f/eslint-plugin-clean-code, workflow release.yml (the first publish must happen within two days of configuring it).

License

MIT

版本与发布记录

@george2f/eslint-plugin-clean-code 共发布 5 个版本,首次发布于 2026/10/15;过去 12 个月发布了 5 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.5.0latest2026/10/1927 天前
0.4.12026/10/151 个月前
0.4.02026/10/151 个月前
0.3.02026/10/151 个月前
0.0.0-stage2026/10/151 个月前

关于 @george2f/eslint-plugin-clean-code 的常见问题

@george2f/eslint-plugin-clean-code 是什么?

ESLint rules derived from the book Clean Code (Robert C. Martin)

如何安装 @george2f/eslint-plugin-clean-code?

在项目目录运行 npm install @george2f/eslint-plugin-clean-code,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:eslint(^8.57.0 || ^9.0.0 || ^10.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@george2f/eslint-plugin-clean-code 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@george2f/eslint-plugin-clean-code 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@george2f/eslint-plugin-clean-code 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js ^18.18.0 || ^20.9.0 || >=21.1.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@george2f/eslint-plugin-clean-code 可以商用吗?

@george2f/eslint-plugin-clean-code 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@george2f/eslint-plugin-clean-code 的下载量有多少?

根据 npm 官方下载统计,@george2f/eslint-plugin-clean-code 在 2026/10/16 – 2026/11/14 这 30 天内被下载 8,928 次,日均约 298 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@george2f/eslint-plugin-clean-code 还在维护吗?

最新版本 0.5.0 发布于 2026/10/19(27 天前);至今共发布 5 个版本,其中过去 12 个月发布了 5 个;首次发布于 2026/10/15。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。