跳转到内容

Rules

Below the list of rules supported by Biome, divided by group. Here’s a legend of the emojis:

  • The icon indicates that the rule is part of the recommended rules.
  • The icon indicates that the rule provides a code action (fix) that is safe to apply.
  • The icon indicates that the rule provides a code action (fix) that is unsafe to apply.
  • The icon indicates that the rule is applied to JavaScript and super languages files.
  • The icon indicates that the rule is applied to TypeScript and TSX files.
  • The icon indicates that the rule is applied to JSON files.
  • The icon indicates that the rule is applied to CSS files.

Rules focused on preventing accessibility problems.

Rule nameDescriptionProperties
noAccessKeyEnforce that the accessKey attribute is not used on any HTML element.
noAriaHiddenOnFocusableEnforce that aria-hidden=“true” is not set on focusable elements.
noAriaUnsupportedElementsEnforce that elements that do not support ARIA roles, states, and properties do not have those attributes.
noAutofocusEnforce that autoFocus prop is not used on elements.
noBlankTargetDisallow target=“_blank” attribute without rel=“noreferrer”
noDistractingElementsEnforces that no distracting elements are used.
noHeaderScopeThe scope prop should be used only on <th> elements.
noInteractiveElementToNoninteractiveRoleEnforce that non-interactive ARIA roles are not assigned to interactive HTML elements.
noNoninteractiveElementToInteractiveRoleEnforce that interactive ARIA roles are not assigned to non-interactive HTML elements.
noNoninteractiveTabindexEnforce that tabIndex is not assigned to non-interactive HTML elements.
noPositiveTabindexPrevent the usage of positive integers on tabIndex property
noRedundantAltEnforce img alt prop does not contain the word “image”, “picture”, or “photo”.
noRedundantRolesEnforce explicit role property is not the same as implicit/default role property on an element.
noSvgWithoutTitleEnforces the usage of the title element for the svg element.
useAltTextEnforce that all elements that require alternative text have meaningful information to relay back to the end user.
useAnchorContentEnforce that anchors have content and that the content is accessible to screen readers.
useAriaActivedescendantWithTabindexEnforce that tabIndex is assigned to non-interactive HTML elements with aria-activedescendant.
useAriaPropsForRoleEnforce that elements with ARIA roles must have all required ARIA attributes for that role.
useButtonTypeEnforces the usage of the attribute type for the element button
useHeadingContentEnforce that heading elements (h1, h2, etc.) have content and that the content is accessible to screen readers. Accessible means that it is not hidden using the aria-hidden prop.
useHtmlLangEnforce that html element has lang attribute.
useIframeTitleEnforces the usage of the attribute title for the element iframe.
useKeyWithClickEventsEnforce onClick is accompanied by at least one of the following: onKeyUp, onKeyDown, onKeyPress.
useKeyWithMouseEventsEnforce onMouseOver / onMouseOut are accompanied by onFocus / onBlur.
useMediaCaptionEnforces that audio and video elements must have a track for captions.
useValidAnchorEnforce that all anchors are valid, and they are navigable elements.
useValidAriaPropsEnsures that ARIA properties aria-* are all valid.
useValidAriaRoleElements with ARIA roles must use a valid, non-abstract ARIA role.
useValidAriaValuesEnforce that ARIA state and property values are valid.
useValidLangEnsure that the attribute passed to the lang attribute is a correct ISO language and/or country.

Rules that focus on inspecting complex code that could be simplified.

Rule nameDescriptionProperties
noBannedTypesDisallow primitive type aliases and misleading types.
noEmptyTypeParametersDisallow empty type parameters in type aliases and interfaces.
noExcessiveCognitiveComplexityDisallow functions that exceed a given Cognitive Complexity score.
noExcessiveNestedTestSuitesThis rule enforces a maximum depth to nested describe() in test files.
noExtraBooleanCastDisallow unnecessary boolean casts
noForEachPrefer for…of statement instead of Array.forEach.
noMultipleSpacesInRegularExpressionLiteralsDisallow unclear usage of consecutive space characters in regular expression literals
noStaticOnlyClassThis rule reports when a class has no non-static members, such as for a class used exclusively as a static namespace.
noThisInStaticDisallow this and super in static contexts.
noUselessCatchDisallow unnecessary catch clauses.
noUselessConstructorDisallow unnecessary constructors.
noUselessEmptyExportDisallow empty exports that don’t change anything in a module file.
noUselessFragmentsDisallow unnecessary fragments
noUselessLabelDisallow unnecessary labels.
noUselessLoneBlockStatementsDisallow unnecessary nested block statements.
noUselessRenameDisallow renaming import, export, and destructured assignments to the same name.
noUselessSwitchCaseDisallow useless case in switch statements.
noUselessTernaryDisallow ternary operators when simpler alternatives exist.
noUselessThisAliasDisallow useless this aliasing.
noUselessTypeConstraintDisallow using any or unknown as type constraint.
noVoidDisallow the use of void operators, which is not a familiar operator.
noWithDisallow with statements in non-strict contexts.
useArrowFunctionUse arrow functions over function expressions.
useFlatMapPromotes the use of .flatMap() when map().flat() are used together.
useLiteralKeysEnforce the usage of a literal access to properties over computed property access.
useOptionalChainEnforce using concise optional chain instead of chained logical expressions.
useRegexLiteralsEnforce the use of the regular expression literals instead of the RegExp constructor if possible.
useSimpleNumberKeysDisallow number literal object member names which are not base10 or uses underscore as separator
useSimplifiedLogicExpressionDiscard redundant terms from logical expressions.

Rules that detect code that is guaranteed to be incorrect or useless.

Rule nameDescriptionProperties
noChildrenPropPrevent passing of children as props.
noConstAssignPrevents from having const variables being re-assigned.
noConstantConditionDisallow constant expressions in conditions
noConstantMathMinMaxClampDisallow the use of Math.min and Math.max to clamp a value where the result itself is constant.
noConstructorReturnDisallow returning a value from a constructor.
noEmptyCharacterClassInRegexDisallow empty character classes in regular expression literals.
noEmptyPatternDisallows empty destructuring patterns.
noFlatMapIdentityDisallow to use unnecessary callback on flatMap.
noGlobalObjectCallsDisallow calling global object properties as functions
noInnerDeclarationsDisallow function and var declarations that are accessible outside their block.
noInvalidConstructorSuperPrevents the incorrect use of super() inside classes. It also checks whether a call super() is missing from classes that extends other constructors.
noInvalidNewBuiltinDisallow new operators with global non-constructor functions.
noInvalidUseBeforeDeclarationDisallow the use of variables and function parameters before their declaration
noNewSymbolDisallow new operators with the Symbol object.
noNodejsModulesForbid the use of Node.js builtin modules.
noNonoctalDecimalEscapeDisallow \8 and \9 escape sequences in string literals.
noPrecisionLossDisallow literal numbers that lose precision
noRenderReturnValuePrevent the usage of the return value of React.render.
noSelfAssignDisallow assignments where both sides are exactly the same.
noSetterReturnDisallow returning a value from a setter
noStringCaseMismatchDisallow comparison of expressions modifying the string case with non-compliant value.
noSwitchDeclarationsDisallow lexical declarations in switch clauses.
noUndeclaredVariablesPrevents the usage of variables that haven’t been declared inside the document.
noUnnecessaryContinueAvoid using unnecessary continue.
noUnreachableDisallow unreachable code
noUnreachableSuperEnsures the super() constructor is called exactly once on every code path in a class constructor before this is accessed if the class has a superclass
noUnsafeFinallyDisallow control flow statements in finally blocks.
noUnsafeOptionalChainingDisallow the use of optional chaining in contexts where the undefined value is not allowed.
noUnusedImportsDisallow unused imports.
noUnusedLabelsDisallow unused labels.
noUnusedPrivateClassMembersDisallow unused private class members
noUnusedVariablesDisallow unused variables.
noVoidElementsWithChildrenThis rules prevents void elements (AKA self-closing elements) from having children.
noVoidTypeReturnDisallow returning a value from a function with the return type ‘void’
useArrayLiteralsDisallow Array constructors.
useExhaustiveDependenciesEnforce all dependencies are correctly specified in a React hook.
useHookAtTopLevelEnforce that all React hooks are being called from the Top Level component functions.
useIsNanRequire calls to isNaN() when checking for NaN.
useJsxKeyInIterableDisallow missing key props in iterators/collection literals.
useValidForDirectionEnforce “for” loop update clause moving the counter in the right direction.
useYieldRequire generator functions to contain yield.

New rules that are still under development.

Nursery rules require explicit opt-in via configuration on stable versions because they may still have bugs or performance problems. They are enabled by default on nightly builds, but as they are unstable their diagnostic severity may be set to either error or warning, depending on whether we intend for the rule to be recommended or not when it eventually gets stabilized. Nursery rules get promoted to other groups once they become stable or may be removed.

Rules that belong to this group are not subject to semantic version.

Rule nameDescriptionProperties
noConsoleDisallow the use of console.
noDoneCallbackDisallow using a callback in asynchronous tests and hooks.
noDuplicateAtImportRulesDisallow duplicate @import rules.
noDuplicateElseIfDisallow duplicate conditions in if-else-if chains
noDuplicateFontNamesDisallow duplicate names within font families.
noDuplicateJsonKeysDisallow two keys with the same name inside a JSON object.
noDuplicateSelectorsKeyframeBlockDisallow duplicate selectors within keyframe blocks.
noEmptyBlockDisallow CSS empty blocks.
noEvolvingTypesDisallow variables from evolving into any type through reassignments.
noImportantInKeyframeDisallow invalid !important within keyframe declarations
noInvalidPositionAtImportRuleDisallow the use of @import at-rules in invalid positions.
noLabelWithoutControlEnforce that a label element or component has a text label and an associated input.
noMisplacedAssertionChecks that the assertion function, for example expect, is placed inside an it() function call.
noReactSpecificPropsPrevents React-specific JSX properties from being used.
noRestrictedImportsDisallow specified modules when loaded by import or require.
noUndeclaredDependenciesDisallow the use of dependencies that aren’t specified in the package.json.
noUnknownFunctionDisallow unknown CSS value functions.
noUnknownMediaFeatureNameDisallow unknown media feature names.
noUnknownPropertyDisallow unknown properties.
noUnknownSelectorPseudoElementDisallow unknown pseudo-element selectors.
noUnknownUnitDisallow unknown CSS units.
noUnmatchableAnbSelectorDisallow unmatchable An+B selectors.
noUnusedFunctionParametersDisallow unused function parameters.
noUselessStringConcatDisallow unnecessary concatenation of string or template literals.
noUselessUndefinedInitializationDisallow initializing variables to undefined.
noYodaExpressionDisallow the use of yoda expressions.
useAdjacentOverloadSignaturesDisallow the use of overload signatures that are not next to each other.
useConsistentBuiltinInstantiationEnforce the use of new for all builtins, except String, Number, Boolean, Symbol and BigInt.
useDateNowUse Date.now() to get the number of milliseconds since the Unix Epoch.
useDefaultSwitchClauseRequire the default clause in switch statements.
useErrorMessageEnforce passing a message value when creating a built-in error.
useExplicitLengthCheckEnforce explicitly comparing the length, size, byteLength or byteOffset property of a value.
useFocusableInteractiveElements with an interactive role and interaction handlers must be focusable.
useGenericFontNamesDisallow a missing generic family keyword within font families.
useImportExtensionsEnforce file extensions for relative imports.
useImportRestrictionsDisallows package private imports.
useNumberToFixedDigitsArgumentEnforce using the digits argument with Number#toFixed().
useSemanticElementsIt detects the use of role attributes in JSX elements and suggests using semantic elements instead.
useSortedClassesEnforce the sorting of CSS utility classes.
useStrictModeEnforce the use of the directive “use strict” in script files.
useThrowNewErrorRequire new when throwing an error.
useThrowOnlyErrorDisallow throwing non-Error values.
useTopLevelRegexRequire regex literals to be declared at the top level.

Rules catching ways your code could be written to run faster, or generally be more efficient.

Rule nameDescriptionProperties
noAccumulatingSpreadDisallow the use of spread () syntax on accumulators.
noBarrelFileDisallow the use of barrel file.
noDeleteDisallow the use of the delete operator.
noReExportAllAvoid re-export all.

Rules that detect potential security flaws.

Rule nameDescriptionProperties
noDangerouslySetInnerHtmlPrevent the usage of dangerous JSX props
noDangerouslySetInnerHtmlWithChildrenReport when a DOM element or a component uses both children and dangerouslySetInnerHTML prop.
noGlobalEvalDisallow the use of global eval().

Rules enforcing a consistent and idiomatic way of writing your code.

Rule nameDescriptionProperties
noArgumentsDisallow the use of arguments.
noCommaOperatorDisallow comma operator.
noDefaultExportDisallow default exports.
noImplicitBooleanDisallow implicit true values on JSX boolean attributes
noInferrableTypesDisallow type annotations for variables, parameters, and class properties initialized with a literal expression.
noNamespaceDisallow the use of TypeScript’s namespaces.
noNamespaceImportDisallow the use of namespace imports.
noNegationElseDisallow negation in the condition of an if statement if it has an else clause.
noNonNullAssertionDisallow non-null assertions using the ! postfix operator.
noParameterAssignDisallow reassigning function parameters.
noParameterPropertiesDisallow the use of parameter properties in class constructors.
noRestrictedGlobalsThis rule allows you to specify global variable names that you don’t want to use in your application.
noShoutyConstantsDisallow the use of constants which its value is the upper-case version of its name.
noUnusedTemplateLiteralDisallow template literals if interpolation and special-character handling are not needed
noUselessElseDisallow else block when the if block breaks early.
noVarDisallow the use of var
useAsConstAssertionEnforce the use of as const over literal type and type annotation.
useBlockStatementsRequires following curly brace conventions.
useCollapsedElseIfEnforce using else if instead of nested if in else clauses.
useConsistentArrayTypeRequire consistently using either T[] or Array<T>
useConstRequire const declarations for variables that are only assigned once.
useDefaultParameterLastEnforce default function parameters and optional function parameters to be last.
useEnumInitializersRequire that each enum member value be explicitly initialized.
useExponentiationOperatorDisallow the use of Math.pow in favor of the ** operator.
useExportTypePromotes the use of export type for types.
useFilenamingConventionEnforce naming conventions for JavaScript and TypeScript filenames.
useForOfThis rule recommends a for-of loop when in a for loop, the index used to extract an item from the iterated array.
useFragmentSyntaxThis rule enforces the use of <>…</> over <Fragment>…</Fragment>.
useImportTypePromotes the use of import type for types.
useLiteralEnumMembersRequire all enum members to be literal values.
useNamingConventionEnforce naming conventions for everything across a codebase.
useNodeAssertStrictPromotes the usage of node:assert /strict over node:assert .
useNodejsImportProtocolEnforces using the node: protocol for Node.js builtin modules.
useNumberNamespaceUse the Number properties instead of global ones.
useNumericLiteralsDisallow parseInt() and Number.parseInt() in favor of binary, octal, and hexadecimal literals
useSelfClosingElementsPrevent extra closing tags for components without children
useShorthandArrayTypeWhen expressing array types, this rule promotes the usage of T[] shorthand instead of Array<T>.
useShorthandAssignRequire assignment operator shorthand where possible.
useShorthandFunctionTypeEnforce using function types instead of object type with call signatures.
useSingleCaseStatementEnforces switch clauses have a single statement, emits a quick fix wrapping the statements in a block.
useSingleVarDeclaratorDisallow multiple variable declarations in the same variable statement
useTemplatePrefer template literals over string concatenation.
useWhileEnforce the use of while loops instead of for loops when the initializer and update expressions are not needed.

Rules that detect code that is likely to be incorrect or useless.

Rule nameDescriptionProperties
noApproximativeNumericConstantUse standard constants instead of approximated literals.
noArrayIndexKeyDiscourage the usage of Array index in keys.
noAssignInExpressionsDisallow assignments in expressions.
noAsyncPromiseExecutorDisallows using an async function as a Promise executor.
noCatchAssignDisallow reassigning exceptions in catch clauses.
noClassAssignDisallow reassigning class members.
noCommentTextPrevent comments from being inserted as text nodes
noCompareNegZeroDisallow comparing against -0
noConfusingLabelsDisallow labeled statements that are not loops.
noConfusingVoidTypeDisallow void type outside of generic or return types.
noConsoleLogDisallow the use of console.log
noConstEnumDisallow TypeScript const enum
noControlCharactersInRegexPrevents from having control characters and some escape sequences that match control characters in regular expressions.
noDebuggerDisallow the use of debugger
noDoubleEqualsRequire the use of === and !==
noDuplicateCaseDisallow duplicate case labels.
noDuplicateClassMembersDisallow duplicate class members.
noDuplicateJsxPropsPrevents JSX properties to be assigned multiple times.
noDuplicateObjectKeysPrevents object literals having more than one property declaration for the same name.
noDuplicateParametersDisallow duplicate function parameter name.
noDuplicateTestHooksA describe block should not contain duplicate hooks.
noEmptyBlockStatementsDisallow empty block statements and static blocks.
noEmptyInterfaceDisallow the declaration of empty interfaces.
noExplicitAnyDisallow the any type usage.
noExportsInTestDisallow using export or module.exports in files containing tests
noExtraNonNullAssertionPrevents the wrong usage of the non-null assertion operator (!) in TypeScript files.
noFallthroughSwitchClauseDisallow fallthrough of switch clauses.
noFocusedTestsDisallow focused tests.
noFunctionAssignDisallow reassigning function declarations.
noGlobalAssignDisallow assignments to native objects and read-only global variables.
noGlobalIsFiniteUse Number.isFinite instead of global isFinite.
noGlobalIsNanUse Number.isNaN instead of global isNaN.
noImplicitAnyLetDisallow use of implicit any type on variable declarations.
noImportAssignDisallow assigning to imported bindings
noLabelVarDisallow labels that share a name with a variable
noMisleadingCharacterClassDisallow characters made with multiple code points in character class syntax.
noMisleadingInstantiatorEnforce proper usage of new and constructor.
noMisrefactoredShorthandAssignDisallow shorthand assign when variable appears on both sides.
noPrototypeBuiltinsDisallow direct use of Object.prototype builtins.
noRedeclareDisallow variable, function, class, and type redeclarations in the same scope.
noRedundantUseStrictPrevents from having redundant “use strict”.
noSelfCompareDisallow comparisons where both sides are exactly the same.
noShadowRestrictedNamesDisallow identifiers from shadowing restricted names.
noSkippedTestsDisallow disabled tests.
noSparseArrayDisallow sparse arrays
noSuspiciousSemicolonInJsxIt detects possible “wrong” semicolons inside JSX elements.
noThenPropertyDisallow then property.
noUnsafeDeclarationMergingDisallow unsafe declaration merging between interfaces and classes.
noUnsafeNegationDisallow using unsafe negation.
useAwaitEnsure async functions utilize await.
useDefaultSwitchClauseLastEnforce default clauses in switch statements to be last
useGetterReturnEnforce get methods to always return a value.
useIsArrayUse Array.isArray() instead of instanceof Array.
useNamespaceKeywordRequire using the namespace keyword over the module keyword to declare TypeScript namespaces.
useValidTypeofThis rule verifies the result of typeof $expr unary expressions is being compared to valid values, either string literals containing valid type names or other typeof expressions

The recommended rules are: