README

eslint-plugin-unicorn npm version

Unicorn

More than 300 powerful ESLint rules

Most rules target JavaScript and TypeScript, but some also lint CSS, HTML, JSON, Markdown, SOML, TOML, and YAML when used with the matching ESLint language plugin.

Propose a new rule ➡

We do not accept pull requests because of too much AI slop.

Install

npm install --save-dev eslint eslint-plugin-unicorn

Requires ESLint >=10.4, flat config, and ESM.

You might want to check out XO, which includes this plugin.

Usage

Use a preset config or configure each rule in eslint.config.js.

If you don’t use a preset, set the same languageOptions as shown below.

import unicorn from 'eslint-plugin-unicorn';
import {defineConfig} from 'eslint/config';
import globals from 'globals';

export default defineConfig([
	{
		files: ['**/*.js'],
		languageOptions: {
			globals: globals.builtin,
		},
		plugins: {
			unicorn,
		},
		rules: {
			'unicorn/prefer-module': 'error',
			'unicorn/…': 'error',
		},
	},
	// …
]);

For TypeScript, scope Unicorn to TypeScript files and configure a TypeScript parser for the same config object:

import typescriptEslintParser from '@typescript-eslint/parser';
import unicorn from 'eslint-plugin-unicorn';
import {defineConfig} from 'eslint/config';
import globals from 'globals';

export default defineConfig([
	{
		files: ['**/*.ts'],
		languageOptions: {
			globals: globals.builtin,
			parser: typescriptEslintParser,
		},
		plugins: {
			unicorn,
		},
		rules: {
			'unicorn/prefer-module': 'error',
			'unicorn/…': 'error',
		},
	},
	// …
]);

Rules

💼 Configurations enabled in.
✅ Set in the recommended configuration.
🎨 Set in the recommended-css configuration.
🌐 Set in the recommended-html configuration.
🧩 Set in the recommended-json configuration.
📚 Set in the recommended-markdown configuration.
💎 Set in the recommended-soml configuration.
🛠️ Set in the recommended-toml configuration.
📋 Set in the recommended-yaml configuration.
☑️ Set in the unopinionated configuration.
🔧 Automatically fixable by the --fix CLI option.
💡 Manually fixable by editor suggestions.
💭 Requires type information.

Name Description 💼 🔧 💡 💭
better-dom-traversing Prefer better DOM traversal APIs. ✅ ☑️ 💡
catch-error-name Enforce a specific parameter name in catch clauses. ✅ 🔧
class-reference-in-static-methods Enforce consistent class references in static methods. ✅ 💡
comma-spacing Enforce consistent spacing before and after commas in JSON and SOML. 🔧
comment-content Enforce better comment content. 🔧
consistent-arrow-return-style Enforce a consistent return style for multiline arrow function bodies. 🔧
consistent-assert Enforce consistent assertion style with node:assert. ✅ 🔧
consistent-boolean-name Enforce consistent naming for boolean names. ✅ 🔧 💡
consistent-class-member-order Enforce consistent class member order. ✅ 💡
consistent-compound-words Enforce consistent spelling of compound words in identifiers. ✅ 🎨 🌐 🧩 💎 🛠️ 📋 ☑️ 💡
consistent-conditional-object-spread Enforce consistent conditional object spread style. ✅ 🔧
consistent-date-clone Prefer passing Date directly to the constructor when cloning. ✅ ☑️ 🔧
consistent-destructuring Use destructured variables over properties. 💡
consistent-empty-array-spread Prefer consistent types when spreading a ternary in an array literal. ✅ 🔧
consistent-existence-index-check Enforce consistent style for element existence checks with indexOf(), lastIndexOf(), findIndex(), and findLastIndex(). ✅ ☑️ 🔧
consistent-export-decorator-position Enforce consistent decorator position on exported classes. ✅ ☑️ 🔧
consistent-function-scoping Move function definitions to the highest possible scope. ✅
consistent-function-style Enforce function syntax by role. 💡
consistent-json-file-read Enforce consistent JSON file reads before JSON.parse(). ✅ 🔧
consistent-optional-chaining Enforce consistent optional chaining for same-base member access. ✅ ☑️ 💡
consistent-template-literal-escape Enforce consistent style for escaping ${ in template literals. ✅ 🔧
consistent-tuple-labels Enforce consistent labels on tuple type elements. ✅
custom-error-definition Enforce correct Error subclassing. 🔧
default-export-style Enforce consistent default export declarations. ✅ 🔧 💡
dom-node-dataset Enforce consistent style for DOM element dataset access. ✅ ☑️ 🔧 💡
empty-brace-spaces Enforce no spaces between braces. ✅ 🎨 🧩 💎 🛠️ 📋 🔧
error-message Enforce passing a message value when creating a built-in error. ✅ ☑️
escape-case Require escape sequences to use uppercase or lowercase values. ✅ 🎨 🧩 💎 🛠️ 📋 ☑️ 🔧
expiring-todo-comments Add expiration conditions to TODO comments. ✅ 🎨 🌐 🧩 📚 💎 🛠️ 📋 ☑️
explicit-length-check Enforce explicitly comparing the length or size property of a value. ✅ 🔧 💡
explicit-timer-delay Enforce or disallow explicit delay argument for setTimeout() and setInterval(). ✅ ☑️ 🔧
filename-case Enforce a case style for filenames and directory names. ✅ 🎨 🌐 🧩 📚 💎 🛠️ 📋
id-match Require identifiers to match a specified regular expression.
import-style Enforce specific import styles per module. ✅ ☑️
indent Enforce consistent indentation in JSON and CSS. 🔧
isolated-functions Prevent usage of variables from outside the scope of isolated functions. ✅
iteration-fallback-style Enforce a consistent style for optional loop sources. 🔧
key-name-casing Enforce a case style for data keys.
logical-assignment-operators Require or disallow logical assignment operator shorthand ✅ 🔧 💡
max-nested-calls Limit the depth of nested calls. ✅
name-replacements Enforce replacements for variable, property, and filenames. ✅ 🎨 🌐 🧩 📚 💎 🛠️ 📋 🔧 💡
new-for-builtins Enforce correct use of new for builtin constructors. ✅ ☑️ 🔧 💡
no-abusive-eslint-disable Enforce specifying rules to disable in eslint-disable comments. ✅ 🎨 🌐 🧩 📚 💎 🛠️ 📋 ☑️
no-accessor-recursion Disallow recursive access to this within getters and setters. ✅ ☑️
no-accidental-bitwise-operator Disallow bitwise operators where a logical operator was likely intended. ✅ ☑️ 💡
no-anonymous-default-export Disallow anonymous functions and classes as the default export. ✅ ☑️ 💡
no-array-callback-reference Prevent passing a function reference directly to iterator methods. ✅ 💡
no-array-concat-in-loop Disallow array accumulation with Array#concat() in loops. ✅
no-array-fill-with-reference-type Disallow using reference values as Array#fill() values. ✅ ☑️
no-array-from-fill Disallow .fill() after Array.from({length: …}). ✅ ☑️
no-array-front-mutation Disallow front-of-array mutation.
no-array-method-this-argument Disallow using the this argument in array methods. ✅ ☑️ 🔧 💡
no-array-reduce Disallow Array#reduce() and Array#reduceRight(). ✅ 🔧 💡
no-array-reverse Prefer Array#toReversed() over Array#reverse(). ✅ ☑️ 💡
no-array-sort Prefer Array#toSorted() over Array#sort(). ✅ ☑️ 💡
no-array-sort-for-min-max Disallow sorting arrays to get the minimum or maximum value. ✅ ☑️ 💡
no-array-splice Prefer Array#toSpliced() over Array#splice(). ✅ 💡
no-asterisk-prefix-in-documentation-comments Disallow asterisk prefixes and shared indentation in multiline comments. ✅ 🎨 🧩 💎 🔧
no-async-iterator-callback Disallow asynchronous callbacks in synchronous iterator helpers. ✅ ☑️
no-async-promise-finally Disallow async functions as Promise#finally() callbacks. ✅ ☑️
no-await-expression-member Disallow member access from await expression. ✅ 🔧
no-await-in-promise-methods Disallow using await in Promise method parameters. ✅ ☑️ 💡
no-barrel-files Disallow barrel files.
no-blob-to-file Disallow unnecessary Blob to File conversion. ✅ ☑️ 💡
no-boolean-sort-comparator Disallow boolean-returning sort comparators. ✅ ☑️ 💡
no-break-in-nested-loop Disallow break and optionally continue in nested loops and switches inside loops. ✅
no-canvas-to-image Prefer drawing canvases directly instead of converting them to images. ✅ ☑️
no-chained-comparison Disallow chained comparisons such as a < b < c. ✅ ☑️ 💡
no-collection-bracket-access Disallow accessing Map, Set, WeakMap, and WeakSet entries with bracket notation. ✅ ☑️ 💡
no-computed-property-existence-check Disallow dynamic object property existence checks. ✅ 💡
no-conflicting-constraints Disallow conflicting CSS query and HTML form constraints. ✅ 🎨 🌐 ☑️
no-confusing-array-splice Disallow confusing uses of Array#{splice,toSpliced}(). ✅ 💡
no-confusing-array-with Disallow confusing uses of Array#with(). ✅
no-console-spaces Do not use leading/trailing space between console.log parameters. ✅ ☑️ 🔧
no-constant-zero-expression Disallow arithmetic and bitwise operations that always evaluate to 0. ✅ ☑️ 💡
no-declarations-before-early-exit Disallow declarations before conditional early exits when they are only used after the exit. ✅ ☑️ 🔧
no-document-cookie Do not use document.cookie directly. ✅ ☑️
no-double-comparison Disallow two comparisons of the same operands that can be combined into one. ✅ ☑️ 💡
no-duplicate-if-branches Disallow duplicate adjacent branches in if chains. ✅
no-duplicate-logical-operands Disallow adjacent duplicate operands in logical expressions. ✅ ☑️ 🔧 💡
no-duplicate-loops Disallow .map() and .filter() in for…of and for await…of loop headers. ✅
no-duplicate-set-values Disallow duplicate values in Set constructor array literals. ✅
no-empty-file Disallow empty files. ✅ 🎨 🌐 🧩 📚 🛠️ 📋 ☑️
no-empty-link-text Disallow empty link text in Markdown. 📚
no-error-property-assignment Disallow assigning to built-in error properties. ✅ ☑️
no-exports-in-scripts Disallow exports in scripts. ✅ ☑️
no-for-each Prefer for…of over the forEach method. ✅ ☑️ 🔧 💡
no-for-loop Do not use a for loop that can be replaced with a for-of loop. ✅ 🔧
no-global-object-property-assignment Disallow assigning properties on the global object. ✅ ☑️
no-immediate-mutation Disallow immediate mutation after assignment and initialization immediately after declaration. ✅ 🔧 💡
no-impossible-length-comparison Disallow impossible comparisons against .length or .size. ✅ ☑️
no-incomplete-accessor-override Disallow class accessors that hide an inherited getter or setter. ✅ ☑️
no-incorrect-query-selector Disallow incorrect querySelector() and querySelectorAll() usage. ✅ 🔧
no-incorrect-template-string-interpolation Disallow incorrect template literal interpolation syntax. ✅ 💡
no-ineffective-csp-directives Disallow ineffective CSP directives in <meta> elements. ✅ 🌐 ☑️
no-instanceof-builtins Disallow instanceof with built-in objects ✅ ☑️ 🔧 💡
no-invalid-argument-count Disallow calling functions and constructors with an invalid number of arguments. ✅ ☑️
no-invalid-boolean-attribute-value Disallow invalid values for HTML boolean attributes. ✅ ☑️ 💡
no-invalid-character-comparison Disallow comparing a single character from a string to a multi-character string. ✅ ☑️
no-invalid-dom-token Disallow invalid DOM tokens. ✅ ☑️ 💡
no-invalid-fetch-options Disallow invalid options in fetch() and new Request(). ✅ ☑️
no-invalid-file-input-accept Disallow invalid accept values on file inputs. 🔧
no-invalid-integrity Disallow invalid subresource integrity metadata. ✅ 🌐 ☑️
no-invalid-intl-options Disallow invalid or ignored Intl options. ✅ ☑️ 💡
no-invalid-property-descriptor Disallow invalid property descriptors. ✅ ☑️ 💡
no-invalid-remove-event-listener Prevent calling EventTarget#removeEventListener() with the result of an expression. ✅ ☑️
no-invalid-response-options Disallow invalid options in new Response(), Response.json(), and Response.redirect(). ✅ ☑️ 💡
no-invalid-style-set-property Disallow invalid arguments to CSSStyleDeclaration#setProperty(). ✅ ☑️ 💡
no-invalid-temporal-arithmetic Disallow statically known invalid Temporal arithmetic. ✅ ☑️ 💡
no-invalid-url-protocol-comparison Disallow invalid protocol strings in comparisons with URL#protocol. ✅ ☑️ 🔧
no-invalid-well-known-symbol-methods Disallow invalid implementations of well-known symbol methods. ✅ ☑️ 🔧 💡
no-javascript-url Disallow javascript: URLs in Markdown.
no-keyword-prefix Disallow identifiers starting with new or class.
no-late-current-target-access Disallow accessing event.currentTarget after the synchronous event dispatch has finished. ✅
no-late-event-control Disallow event-control method calls after the synchronous event dispatch has finished. ✅
no-leading-empty-lines Disallow empty lines at the beginning of a file. ✅ 🎨 🌐 🧩 📚 💎 🛠️ 📋 🔧
no-lonely-if Disallow if statements as the only statement in if blocks without else. ✅ ☑️ 🔧
no-loop-iterable-mutation Disallow mutating a loop iterable during iteration. ✅
no-loss-of-precision Disallow numeric literals that lose precision when represented as IEEE 754 binary64 values.
no-magic-array-flat-depth Disallow a magic number as the depth argument in Array#flat(…). ✅ ☑️
no-manually-wrapped-comments Disallow manually wrapped comments. 🔧
no-mismatched-map-key Disallow checking a Map key before accessing a different key. ✅
no-misrefactored-assignment Disallow misrefactored compound assignments where the target is duplicated in the right-hand side. ✅ ☑️ 💡
no-missing-local-resource Disallow references to missing local resources. 🔧
no-multiple-promise-resolver-calls Disallow calling Promise executor resolver functions more than once on the same execution path. ✅ ☑️
no-named-default Disallow named usage of default import and export. ✅ ☑️ 🔧
no-negated-array-predicate Disallow negated array predicate calls. ✅ ☑️ 🔧
no-negated-comparison Disallow negated comparisons. ✅ ☑️ 🔧
no-negated-condition Disallow negated conditions. ✅ ☑️ 🔧
no-negation-in-equality-check Disallow negated expression in equality check. ✅ ☑️ 💡
no-nested-ternary Disallow nested ternary expressions. ✅ 🔧
no-new-array Disallow new Array(). ✅ ☑️ 🔧 💡
no-new-buffer Enforce the use of Buffer.from() and Buffer.alloc() instead of the deprecated new Buffer(). ✅ ☑️ 🔧 💡
no-non-function-verb-prefix Disallow non-function values with function-style verb prefixes. ✅ 💭
no-nonstandard-builtin-properties Disallow non-standard properties on built-in objects. ✅ ☑️
no-null Disallow the use of the null literal. ✅ 🔧 💡
no-object-as-default-parameter Disallow the use of objects as default parameters. ✅ ☑️
no-object-methods-with-collections Disallow Object methods with Map or Set. ✅ 💡
no-optional-chaining-on-undeclared-variable Disallow optional chaining on undeclared variables. ✅
no-prevent-default-in-passive-listener Disallow ineffective preventDefault() calls in passive event listeners. ✅ ☑️ 💡
no-process-exit Disallow process.exit(). ✅ ☑️
no-redundant-comparison Disallow comparisons made redundant by an equality check in the same logical AND. ✅ ☑️ 🔧 💡
no-repeated-call-wrappers Disallow repeating the same wrapper at every call to a function.
no-return-array-push Disallow using the return value of Array#push() and Array#unshift(). ✅ 💡
no-selector-as-dom-name Disallow selector syntax in DOM names. ✅ 🔧
no-shorthand-property-overrides Disallow shorthand properties that override related longhand properties. ✅ 🎨 ☑️
no-single-promise-in-promise-methods Disallow passing single-element arrays to Promise methods. ✅ ☑️ 🔧 💡
no-static-only-class Disallow classes that only have static members. ✅ ☑️ 🔧
no-subtraction-comparison Prefer comparing values directly over subtracting and comparing to 0. ✅ ☑️ 🔧 💡
no-thenable Disallow then property. ✅ ☑️
no-this-assignment Disallow assigning this to a variable. ✅ ☑️
no-this-outside-of-class Disallow this outside of classes. ✅
no-top-level-assignment-in-function Disallow assigning to top-level variables from inside functions. ✅
no-top-level-side-effects Disallow top-level side effects in exported modules. ✅
no-transition-all Disallow all as a transition property. ✅ 🎨 ☑️
no-typeof-undefined Disallow comparing undefined using typeof. ✅ ☑️ 🔧 💡
no-uncalled-method Disallow referencing methods without calling them. ✅
no-undeclared-class-members Require class members to be declared. ✅ 💡
no-unnecessary-array-flat-depth Disallow using 1 as the depth argument of Array#flat(). ✅ ☑️ 🔧
no-unnecessary-array-flat-map Disallow unnecessary use of Array#flatMap(). ✅ 🔧 💡
no-unnecessary-array-splice-count Disallow using .length or Infinity as the deleteCount or skipCount argument of Array#{splice,toSpliced}(). ✅ ☑️ 🔧
no-unnecessary-await Disallow awaiting non-promise values. ✅ ☑️ 🔧
no-unnecessary-boolean-comparison Disallow unnecessary comparisons against boolean literals. ✅ 🔧
no-unnecessary-default-arguments Disallow arguments that match their parameter defaults. 🔧 💡
no-unnecessary-fetch-options Disallow unnecessary options in fetch() and new Request(). ✅ ☑️ 🔧
no-unnecessary-global-this Disallow unnecessary globalThis references. ✅ ☑️ 🔧
no-unnecessary-nested-ternary Disallow unnecessary nested ternary expressions. ✅ ☑️ 🔧 💡
no-unnecessary-parameters Disallow parameters that receive the same value at every call. ✅ 🔧 💡
no-unnecessary-polyfills Enforce the use of built-in methods instead of unnecessary polyfills. ✅ ☑️
no-unnecessary-slice-end Disallow using .length or Infinity as the end argument of {Array,String,TypedArray}#slice(). ✅ ☑️ 🔧
no-unnecessary-splice Disallow Array#splice() when simpler alternatives exist. ✅ 🔧
no-unnecessary-string-trim Disallow String#trim() before String#startsWith() or String#endsWith(). ✅ ☑️ 🔧
no-unreadable-array-destructuring Disallow unreadable array destructuring. ✅ ☑️ 🔧
no-unreadable-for-of-expression Disallow unreadable iterable expressions in for…of and for await…of loop headers. ✅
no-unreadable-iife Disallow unreadable IIFEs. ✅ ☑️ 💡
no-unreadable-new-expression Disallow unreadable new expressions.
no-unreadable-object-destructuring Disallow unreadable object destructuring. ✅ ☑️
no-unsafe-buffer-conversion Prevent unsafe use of ArrayBuffer view .buffer. ✅ ☑️ 💡
no-unsafe-dom-html Disallow unsafe DOM HTML APIs.
no-unsafe-json-serialization Disallow known values that JSON serialization cannot represent faithfully. ✅ 💡
no-unsafe-promise-all-settled-values Disallow reading .value from Promise.allSettled() results without a fulfilled status guard. ✅ ☑️
no-unsafe-property-key Disallow unsafe values as property keys. ✅
no-unsafe-sqlite-interpolation Disallow interpolation into SQL strings passed to Node’s node:sqlite APIs. ✅ ☑️
no-unsafe-string-replacement Disallow non-literal replacement values in String#replace() and String#replaceAll(). ✅
no-unused-builtin-method-return Disallow ignoring the return value of selected built-in methods. ✅ ☑️
no-unused-iterator-helper Disallow discarding lazy iterator helpers. ✅ ☑️ 💡
no-unused-properties Disallow unused object properties.
no-url-in-search-params Disallow passing full URLs to URLSearchParams. ✅ ☑️ 💡
no-useless-boolean-cast Disallow unnecessary Boolean() casts in array predicate callbacks. ✅ ☑️ 🔧
no-useless-coercion Disallow useless type coercions of values that are already of the target type. ✅ ☑️ 🔧
no-useless-collection-argument Disallow useless values or fallbacks in Set, Map, WeakSet, or WeakMap. ✅ ☑️ 🔧 💡
no-useless-compound-assignment Disallow useless compound assignments such as x += 0. ✅ ☑️ 💡
no-useless-concat Disallow useless concatenation of literals. ✅ ☑️ 🔧
no-useless-continue Disallow useless continue statements. ✅ ☑️ 🔧
no-useless-delete-check Disallow unnecessary existence checks before deletion. ✅ ☑️ 🔧 💡
no-useless-else Disallow else after a statement that exits. ✅ 🔧
no-useless-error-capture-stack-trace Disallow unnecessary Error.captureStackTrace(…). ✅ ☑️ 🔧
no-useless-fallback-in-spread Disallow useless fallback when spreading in object literals. ✅ ☑️ 🔧
no-useless-iterator-to-array Disallow unnecessary .toArray() on iterators. ✅ ☑️ 🔧 💡
no-useless-length-check Disallow useless array length check. ✅ ☑️ 🔧 💡
no-useless-logical-operand Disallow unnecessary operands in logical expressions involving boolean literals. ✅ ☑️ 🔧
no-useless-override Disallow useless overrides of class methods. ✅ ☑️ 🔧
no-useless-promise-resolve-reject Disallow returning/yielding Promise.resolve/reject() in async functions or promise callbacks ✅ ☑️ 🔧
no-useless-re-export Disallow redundant re-exports. ✅ ☑️
no-useless-recursion Disallow simple recursive function calls that can be replaced with a loop. ✅
no-useless-set-construction Disallow unnecessary Set construction around Set methods. ✅ ☑️ 🔧
no-useless-spread Disallow unnecessary spread. ✅ ☑️ 🔧 💡
no-useless-switch-case Disallow useless case in switch statements. ✅ ☑️ 💡
no-useless-template-literals Disallow useless template literal expressions. ✅ ☑️ 🔧 💡
no-useless-undefined Disallow useless undefined. ✅ ☑️

README 内容过长,已截取前 64 KB。完整内容请前往 GitHub 仓库查看。

评论

暂无评论