JavaScript MIT

eslint-plugin-unicorn

More than 300 powerful ESLint rules

S

sindresorhus

Dernière activité 26 sept. 2026
sindresorhus/eslint-plugin-unicorn

5,3 k

étoiles

496

forks

8

issues ouvertes

eslinteslint-configeslint-plugineslint-rulesjavascriptlinting-rulesnodejsunicornsxo

Ce README est souvent en anglais.

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, 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-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. 🔧
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-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. ✅ ☑️ 🔧 💡
no-using-resource-escape Disallow returning or exporting resources declared with using, including through capturing functions. ✅ ☑️
no-xor-as-exponentiation Disallow the bitwise XOR operator where exponentiation was likely intended. ✅ ☑️ 💡
no-zero-fractions Require consistent decimal numbers without redundant zeros. ✅ 🎨 🧩 🛠️ 📋 ☑️ 🔧
number-literal-case Enforce proper case for numeric literals. ✅ 🎨 🧩 🛠️ 📋 🔧
numeric-separators-style Enforce the style of numeric separators by correctly grouping digits. ✅ 🛠️ ☑️ 🔧
operator-assignment Require assignment operator shorthand where possible. ✅ 🔧 💡
prefer-abort-signal-any Prefer AbortSignal.any() over manually forwarding abort events between signals. ✅ 💡
prefer-abort-signal-timeout Prefer AbortSignal.timeout() over manually aborting an AbortController with setTimeout(). ✅ 💡
prefer-add-event-listener Prefer .addEventListener() and .removeEventListener() over on-functions. ✅ ☑️ 🔧
prefer-add-event-listener-options Prefer an options object over a boolean in .addEventListener(). ✅ ☑️ 🔧
prefer-aggregate-error Prefer AggregateError when throwing collected errors. ✅ ☑️ 🔧
prefer-array-find Prefer .find(…) and .findLast(…) over the first or last element from .filter(…). ✅ ☑️ 🔧
prefer-array-flat Prefer Array#flat() over legacy techniques to flatten arrays. ✅ ☑️ 🔧
prefer-array-flat-map Prefer .flatMap(…) over .map(…).flat() and .filter(…).flatMap(…). ✅ ☑️ 🔧 💡
prefer-array-from-async Prefer Array.fromAsync() over array accumulation loops. ✅ 🔧 💡
prefer-array-from-map Prefer using the Array.from() mapping function argument. ✅ ☑️ 🔧 💡
prefer-array-from-range Prefer Array.from({length}, …) when creating range arrays. ✅ ☑️ 🔧
prefer-array-index-of Prefer Array#{indexOf,lastIndexOf}() over Array#{findIndex,findLastIndex}() when looking for the index of an item. ✅ ☑️ 🔧 💡
prefer-array-iterable-methods Prefer iterating an array directly or with Array#keys() over Array#entries() when the index or value is unused. ✅ 🔧
prefer-array-last-methods Prefer last-oriented array methods over Array#reverse() or Array#toReversed() followed by a method. ✅ ☑️ 💡
prefer-array-slice Prefer Array#slice() over Array#splice() when reading from the returned array. ✅ 💡
prefer-array-some Prefer .some(…) over .filter(…).length check and .{find,findLast,findIndex,findLastIndex}(…). ✅ ☑️ 🔧 💡
prefer-at Prefer .at() method for index access and String#charAt(). ✅ ☑️ 🔧 💡
prefer-await Prefer await over promise chaining. ✅ ☑️ 💡
prefer-bigint-literals Prefer BigInt literals over the constructor. ✅ ☑️ 🔧 💡
prefer-blob-reading-methods Prefer Blob#arrayBuffer() over FileReader#readAsArrayBuffer(…) and Blob#text() over FileReader#readAsText(…). ✅ ☑️
prefer-block-statement-over-iife Prefer block statements over IIFEs used only for scoping. ✅ ☑️ 🔧
prefer-boolean-return Prefer directly returning boolean expressions over if statements. ✅ ☑️ 🔧
prefer-class-fields Prefer class field declarations over this assignments in constructors. ✅ ☑️ 🔧 💡
prefer-classlist-toggle Prefer using Element#classList.toggle() to toggle class names. ✅ ☑️ 🔧 💡
prefer-code-point Prefer String#codePointAt(…) over String#charCodeAt(…) and String.fromCodePoint(…) over String.fromCharCode(…). ✅ ☑️ 💡
prefer-combined-guards Prefer combining consecutive guards with identical exit statements. ✅ 🔧
prefer-continue Prefer early continues over conditionals wrapping the remainder of the loop body. ✅ 🔧
prefer-date-now Prefer Date.now() to get the number of milliseconds since the Unix Epoch. ✅ ☑️ 🔧
prefer-default-parameters Prefer default parameters and destructuring defaults over reassignment and fallback expressions. ✅ ☑️ 💡
prefer-direct-iteration Prefer direct iteration over default iterator method calls. ✅ ☑️ 🔧
prefer-dispose Prefer using using/await using over manual try/finally resource disposal. 💡
prefer-dom-node-append Prefer Element#append() over Node#appendChild(). ✅ ☑️ 🔧
prefer-dom-node-html-methods Prefer .getHTML() and .setHTML() over .innerHTML. ✅ 🔧 💡
prefer-dom-node-remove Prefer childNode.remove() over parentNode.removeChild(childNode). ✅ ☑️ 🔧 💡
prefer-dom-node-replace-children Prefer .replaceChildren() when replacing DOM children. ✅ ☑️ 🔧 💡
prefer-dom-node-text-content Prefer .textContent over .innerText. ✅ ☑️ 💡
prefer-early-return Prefer early returns over conditionals wrapping the remainder of the function body. ✅ ☑️ 🔧 💡
prefer-else-if Prefer else if over adjacent if statements with related conditions. ✅ 🔧 💡
prefer-error-is-error Prefer Error.isError() when checking for errors. 🔧
prefer-escaped-irregular-whitespace Prefer escape sequences for irregular whitespace characters. ✅ 🧩 🛠️ ☑️ 🔧
prefer-event-target Prefer EventTarget over EventEmitter. ✅ ☑️
prefer-export-from Prefer export…from when re-exporting. ✅ 🔧 💡
prefer-flat-math-min-max Prefer flat Math.min() and Math.max() calls over nested calls. ✅ ☑️ 🔧
prefer-get-or-insert-computed Prefer .getOrInsertComputed() when the default value has side effects. ✅ 🔧
prefer-global-number-constants Prefer global numeric constants over Number static properties. ✅ ☑️ 🔧
prefer-global-this Prefer globalThis over window, self, and global. ✅ ☑️ 🔧
prefer-group-by Prefer Object.groupBy() or Map.groupBy() over manual grouping. ✅ 🔧
prefer-has-check Prefer .has() when checking existence. ✅ ☑️ 🔧
prefer-hoisting-branch-code Prefer moving code shared by all branches of an if statement out of the branches. ✅ 🔧 💡
prefer-https Prefer HTTPS over HTTP. ✅ 🎨 🌐 🧩 📚 🛠️ 📋 🔧
prefer-identifier-import-export-specifiers Prefer identifiers over string literals in import and export specifiers. ✅ ☑️ 🔧
prefer-import-meta-properties Prefer import.meta.{dirname,filename} over legacy techniques for getting file paths. 🔧
prefer-includes Prefer .includes() over .indexOf(), .lastIndexOf(), and Array#some() when checking for existence or non-existence. ✅ ☑️ 🔧 💡
prefer-includes-over-repeated-comparisons Prefer .includes() over repeated equality comparisons. ✅
prefer-iterable-in-constructor Prefer passing iterables directly to constructors instead of filling empty collections. ✅ ☑️ 🔧
prefer-iterator-concat Prefer Iterator.concat(…) over temporary spread arrays. 🔧 💡
prefer-iterator-helpers Prefer iterator helpers over temporary arrays from iterators. ✅ ☑️ 💡
prefer-iterator-to-array Prefer Iterator#toArray() over temporary arrays from iterator spreads. ✅ 🔧 💡
prefer-iterator-to-array-at-end Prefer moving .toArray() to the end of iterator helper chains. ✅ ☑️ 💡
prefer-iterator-zip Prefer Iterator.zip() over parallel-array indexing. ✅ 💡
prefer-json-import Prefer JSON imports over reading and parsing JSON files. 💡
prefer-keyboard-event-key Prefer KeyboardEvent#key over deprecated keyboard event properties. ✅ ☑️ 🔧 💡
prefer-literal-ascii Prefer literal printable ASCII characters over escape sequences. ✅ 🎨 🧩 ☑️ 🔧
prefer-location-assign Prefer location.assign() over assigning to location.href. ✅ 🔧
prefer-logical-operator-over-ternary Prefer using a logical operator over a ternary. ✅ ☑️ 🔧 💡
prefer-map-from-entries Prefer new Map() over Object.fromEntries() when using the result as a map. ✅ ☑️ 🔧
prefer-math-abs Prefer Math.abs() over manual absolute value expressions and symmetric range checks. ✅ ☑️ 💡
prefer-math-constants Prefer Math constants over their approximate numeric values. ✅ ☑️ 💡
prefer-math-min-max Prefer Math.min() and Math.max() over ternaries for simple comparisons. ✅ ☑️ 🔧
prefer-math-trunc Prefer Math.trunc() for truncating numbers. ✅ ☑️ 💡
prefer-minimal-ternary Prefer moving ternaries into the minimal varying part of an expression. ✅ ☑️ 🔧 💡
prefer-modern-dom-apis Prefer modern DOM APIs. ✅ ☑️ 🔧
prefer-modern-math-apis Prefer modern Math APIs over legacy patterns. ✅ ☑️ 🔧
prefer-module Prefer JavaScript modules (ESM) over CommonJS. ✅ ☑️ 🔧 💡
prefer-native-coercion-functions Prefer using String, Number, BigInt, Boolean, and Symbol directly. ✅ ☑️ 🔧 💡
prefer-negative-index Prefer negative index over .length - index when possible. ✅ ☑️ 🔧
prefer-node-protocol Prefer using the node: protocol when importing Node.js builtin modules. ✅ ☑️ 🔧
prefer-number-coercion Prefer Number() over parseFloat() and base-10 parseInt(). ✅ ☑️ 💡
prefer-number-is-safe-integer Prefer Number.isSafeInteger() over integer checks. ✅ 💡
prefer-number-properties Prefer Number static methods over global functions and optionally static properties over global constants. ✅ ☑️ 🔧 💡
prefer-object-define-properties Prefer Object.defineProperties() over multiple Object.defineProperty() calls. ✅ ☑️ 🔧
prefer-object-destructuring-defaults Prefer object destructuring defaults over default object literals with spread. ✅ 💡
prefer-object-from-entries Prefer using Object.fromEntries(…) to transform a list of key-value pairs into an object. ✅ ☑️ 🔧
prefer-object-iterable-methods Prefer the most specific Object iterable method. ✅ ☑️ 🔧
prefer-observer-apis Prefer observer APIs over resize and scroll listeners with layout reads. ✅
prefer-optional-catch-binding Prefer omitting the catch binding parameter. ✅ ☑️ 🔧
prefer-path2d Prefer Path2D for repeatedly drawn canvas paths. ✅ ☑️
prefer-private-class-fields Prefer private class fields over the underscore-prefix convention. ✅ 🔧 💡
prefer-promise-static-methods Prefer Promise.resolve() and Promise.reject() over trivial new Promise() calls. ✅ ☑️ 🔧
prefer-promise-try Prefer Promise.try() over promise-wrapping boilerplate. ✅ 🔧
prefer-promise-with-resolvers Prefer Promise.withResolvers() when extracting resolver functions from new Promise(). ✅ ☑️ 🔧
prefer-prototype-methods Prefer borrowing methods from the prototype instead of the instance. ✅ ☑️ 🔧
prefer-query-selector Prefer .querySelector() and .querySelectorAll() over older DOM query methods. ✅ 🔧
prefer-queue-microtask Prefer queueMicrotask() over process.nextTick(), setImmediate(), and setTimeout(…, 0). ✅ ☑️ 🔧
prefer-reflect-apply Prefer Reflect.apply() over Function#apply(). ✅ ☑️ 🔧
prefer-regexp-escape Prefer RegExp.escape() for escaping strings to use in regular expressions. 🔧 💡
prefer-regexp-test Prefer RegExp#test() over String#match(), String#search(), and RegExp#exec(). ✅ ☑️ 🔧 💡
prefer-response-static-json Prefer Response.json() over new Response(JSON.stringify()). ✅ ☑️ 🔧
prefer-scoped-selector Prefer :scope when using element query selector methods. ✅ 💡
prefer-set-has Prefer Set#has() over Array#includes() when checking for existence or non-existence. ✅ ☑️ 🔧 💡
prefer-set-methods Prefer Set methods for Set operations. ✅ 🔧 💡
prefer-set-size Prefer using Set#size instead of Array#length. ✅ ☑️ 🔧
prefer-short-arrow-method Prefer arrow function properties over methods with a single return. 🔧
prefer-short-escape-sequences Prefer shorter alternatives to Unicode escape sequences. ✅ 🧩 🛠️ ☑️ 🔧
prefer-simple-condition-first Prefer simple conditions first in logical expressions. ✅ 🔧
prefer-simple-sort-comparator Prefer a simple comparison function for Array#sort(). ✅ ☑️ 💡
prefer-simplified-conditions Prefer simplified conditions. ✅ ☑️ 🔧
prefer-single-array-predicate Prefer a single Array#some() or Array#every() with a combined predicate. ✅ ☑️ 💡
prefer-single-call Enforce combining multiple Array#{push,unshift}(), Element#classList.{add,remove}(), and importScripts() into one call. ✅ ☑️ 🔧 💡
prefer-single-object-destructuring Prefer a single object destructuring declaration per local const source. ✅ 🔧
prefer-single-replace Enforce combining multiple single-character replacements into a single String#replaceAll() with a regular expression. ✅ ☑️ 🔧
prefer-smaller-scope Prefer declaring variables in the smallest possible scope. ✅ 🔧
prefer-split-limit Prefer String#split() with a limit. ✅ ☑️ 🔧
prefer-spread Prefer the spread operator over Array.from(…), Array#concat(…), Array#{slice,toSpliced}(), and trivial for…of copies. ✅ 🔧 💡
prefer-string-match-all Prefer String#matchAll() over RegExp#exec() loops. ✅ ☑️ 🔧
prefer-string-pad-start-end Prefer String#padStart() and String#padEnd() over manual string padding. ✅ ☑️ 🔧 💡
prefer-string-raw Prefer using the String.raw tag to avoid escaping \. ✅ ☑️ 🔧
prefer-string-repeat Prefer String#repeat() for repeated whitespace. ✅ ☑️ 🔧
prefer-string-replace-all Prefer String#replaceAll() over regex searches with the global flag and String#split().join(). ✅ ☑️ 🔧
prefer-string-slice Prefer String#slice() over String#substr() and String#substring(). ✅ ☑️ 🔧
prefer-string-starts-ends-with Prefer String#startsWith() & String#endsWith() over regexes, String#indexOf() === 0, and slice checks. ✅ ☑️ 🔧 💡
prefer-string-trim-start-end Prefer String#trimStart() / String#trimEnd() over String#trimLeft() / String#trimRight(). ✅ ☑️ 🔧
prefer-structured-clone Prefer using structuredClone to create a deep clone. ✅ ☑️ 💡
prefer-switch Prefer switch over multiple else-if. ✅ ☑️ 🔧 💡
prefer-temporal Prefer Temporal over Date. 🔧 💡
prefer-temporal-conversion Prefer direct Temporal conversion methods. ✅ ☑️ 🔧 💡
prefer-ternary Prefer ternary expressions over simple if statements that return or assign values. ✅ ☑️ 🔧 💡
prefer-then-catch Prefer .then().catch() over .then(…, …) for error handling. ✅ 💡
prefer-toggle-attribute Prefer using Element#toggleAttribute() to toggle attributes. ✅ ☑️ 🔧 💡
prefer-top-level-await Prefer top-level await over top-level promises and async function calls. ✅ ☑️ 💡
prefer-type-error Enforce throwing TypeError in type checking conditions. ✅ ☑️ 🔧
prefer-type-literal-last Require type literals to be last in union types. ✅ 🔧
prefer-uint8array-base64 Prefer Uint8Array#toBase64() and Uint8Array.fromBase64() over legacy base64 conversions and manual postprocessing. 🔧 💡
prefer-uint8array-hex Prefer Uint8Array#toHex() and Uint8Array.fromHex() over manual and Buffer hex conversions. 🔧 💡
prefer-unary-minus Prefer the unary minus operator over multiplying or dividing by -1. ✅ ☑️ 🔧
prefer-unicode-code-point-escapes Prefer Unicode code point escapes over legacy escape sequences. ✅ ☑️ 🔧 💡
prefer-url-can-parse Prefer URL.canParse() over constructing a URL in a try/catch for validation. ✅ ☑️ 🔧
prefer-url-href Prefer URL#href over stringifying a URL. ✅ ☑️ 🔧
prefer-url-search-parameters Prefer URLSearchParams over manually splitting query strings. ✅ ☑️ 💡
prefer-while-loop-condition Prefer putting the condition in the while statement. ✅ ☑️ 🔧
relative-url-style Enforce consistent relative URL style. ✅ 🎨 🌐 📚 ☑️ 🔧 💡
require-array-join-separator Enforce using the separator argument with Array#join(). ✅ ☑️ 🔧
require-array-sort-compare Require a compare function when calling Array#sort() or Array#toSorted(). ✅ ☑️ 💡
require-css-escape Require CSS.escape() for interpolated values in CSS selectors. ✅ ☑️ 🔧
require-frontmatter-fields Require configured YAML frontmatter fields.
require-module-attributes Require non-empty module attributes for imports and exports ✅ ☑️ 🔧
require-module-specifiers Require non-empty specifier list in import and export statements. ✅ ☑️ 🔧 💡
require-number-to-fixed-digits-argument Enforce using the digits argument with Number#toFixed(). ✅ ☑️ 🔧
require-passive-events Require passive event listeners for high-frequency events. ✅ ☑️ 🔧
require-post-message-target-origin Enforce using the targetOrigin argument with window.postMessage(). 💡
require-proxy-trap-boolean-return Require boolean-returning Proxy traps to return booleans. ✅ ☑️ 🔧
require-text-decoder-streaming Require streaming decoding of fetch-body chunks with TextDecoder. ✅ ☑️ 💡
single-line-block-comment-style Enforce a consistent style for single-line block comments. ✅ 🎨 🧩 🔧
string-content Enforce better string content. 🔧 💡
switch-case-braces Enforce consistent brace style for case clauses. ✅ 🔧
switch-case-break-position Enforce consistent break/return/continue/throw position in case clauses. ✅ 🔧
template-indent Fix whitespace-insensitive template indentation. ✅ 🔧
text-encoding-identifier-case Enforce consistent case for text encoding identifiers. ✅ 🎨 🌐 ☑️ 🔧 💡
throw-new-error Require new when creating an error. ✅ ☑️ 🔧
try-complexity Limit the complexity of try blocks.

Non-JavaScript files

While most rules target JavaScript and TypeScript, some also lint other file types when used with the corresponding ESLint language plugin such as @eslint/css, @eslint/json, @eslint/markdown, @html-eslint/eslint-plugin, eslint-plugin-yml, or eslint-plugin-toml.

When linting JSON, CSS, Markdown, HTML, or other non-JavaScript languages in the same ESLint config, scope Unicorn's JavaScript rule config objects with files. Include TypeScript/JSX extensions there only if your config already provides the matching parser/language setup for those files.

For example, keep Unicorn's JavaScript rules scoped separately, and use the non-JavaScript recommended configs for other languages:

import css from '@eslint/css';
import json from '@eslint/json';
import unicorn from 'eslint-plugin-unicorn';
import {defineConfig} from 'eslint/config';

export default defineConfig([
	{
		files: ['**/*.js'],
		plugins: {unicorn},
		extends: ['unicorn/recommended'],
	},
	{
		files: ['**/*.json'],
		plugins: {json, unicorn},
		language: 'json/json',
		extends: ['unicorn/recommended-json'],
	},
	{
		files: ['**/*.css'],
		plugins: {css, unicorn},
		language: 'css/css',
		extends: ['unicorn/recommended-css'],
	},
]);

These rules work on any file type:

These rules also work on specific non-JavaScript languages:

Name CSS HTML JSON Markdown TOML YAML
comma-spacing ✅
consistent-compound-words ✅ ✅ ✅ ✅ ✅
empty-brace-spaces ✅ ✅ ✅ ✅
escape-case ✅ ✅ ✅ ✅
expiring-todo-comments ✅ ✅ ✅ ✅ ✅ ✅
id-match ✅ ✅
indent ✅ ✅
key-name-casing ✅ ✅ ✅
name-replacements ✅ ✅ ✅ ✅ ✅ ✅
no-asterisk-prefix-in-documentation-comments ✅ ✅
no-conflicting-constraints ✅ ✅
no-empty-file ✅ ✅ ✅ ✅ ✅ ✅
no-empty-link-text ✅
no-ineffective-csp-directives ✅
no-invalid-file-input-accept ✅
no-invalid-integrity ✅
no-javascript-url ✅
no-loss-of-precision ✅ ✅ ✅
no-manually-wrapped-comments ✅ ✅ ✅ ✅
no-missing-local-resource ✅ ✅ ✅
no-shorthand-property-overrides ✅
no-transition-all ✅
no-zero-fractions ✅ ✅ ✅ ✅
number-literal-case ✅ ✅ ✅ ✅
numeric-separators-style ✅
prefer-escaped-irregular-whitespace ✅ ✅
prefer-literal-ascii ✅ ✅
prefer-short-escape-sequences ✅ ✅
relative-url-style ✅ ✅ ✅
require-frontmatter-fields ✅
single-line-block-comment-style ✅ ✅
string-content ✅ ✅ ✅ ✅
text-encoding-identifier-case ✅ ✅

CSS

For more CSS rules, see eslint-cssicorn.

Enabled by the recommended-css preset:

Opt-in:

HTML

Enabled by the recommended-html preset:

Opt-in:

JSON

Enabled by the recommended-json preset:

Opt-in:

Markdown

Enabled by the recommended-markdown preset:

Opt-in:

TOML

Enabled by the recommended-toml preset:

Opt-in:

YAML

Enabled by the recommended-yaml preset:

Opt-in:

Deleted and deprecated rules

See the list.

Preset configs

See the ESLint docs for more information about extending config files.

Note: The JavaScript preset configs also enable the correct language options.

This plugin exports a recommended config that enforces good practices.

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

export default defineConfig([
	// …
	{
		files: ['**/*.js'],
		plugins: {
			unicorn,
		},
		extends: [
			'unicorn/recommended',
		],
		rules: {
			'unicorn/prefer-module': 'warn',
		},
	},
]);

These presets enable recommended rules compatible with every dialect listed below. Compatible opt-in rules are disabled, and deprecated rules are excluded. Configure file matching, the language plugin, and language separately. These presets do not configure JavaScript globals or core-rule overrides.

Note

Ideally, a single recommended preset would work for every language. ESLint currently throws when an enabled rule's meta.languages does not support the active language, rather than filtering incompatible rules from shared presets. This requires separate presets per language. Our request for ESLint to support this was closed. If you want a single preset, open a new ESLint issue explaining your use case and referencing that request.

Preset Supported languages
recommended-css css/css
recommended-html html/html
recommended-json json/json, json/jsonc, json/json5
recommended-markdown markdown/commonmark, markdown/gfm
recommended-toml toml/toml
recommended-yaml yml/yaml

For JSONC or JSON5, use recommended-json with language: 'json/jsonc' or language: 'json/json5'. For GFM Markdown, use recommended-markdown with language: 'markdown/gfm'. These choices are independent of the file extension.

For example:

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

export default defineConfig({
	files: ['**/*.json'],
	plugins: {json, unicorn},
	language: 'json/json',
	extends: ['unicorn/recommended-json'],
});

You can also extend a preset directly, for example extends: [unicorn.configs['recommended-json']]. Scope JavaScript presets separately as shown in the configuration examples.

All config

This plugin exports an all config that enables every JavaScript-compatible rule, except deprecated ones.

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

export default defineConfig([
	// …
	{
		files: ['**/*.js'],
		plugins: {
			unicorn,
		},
		extends: [
			'unicorn/all',
		],
		rules: {
			'unicorn/prefer-module': 'warn',
		},
	},
]);

Projets similaires

❤️ JavaScript/TypeScript linter (ESLint wrapper) with great defaults

TypeScriptbest-practicescode-styleeslint
Xxojs
8 k étoiles309

ESLint plugin for Prettier formatting

JavaScripteslint-pluginprettier
Pprettier
3,7 k étoiles213

ESLint rules for Node Security

JavaScripteslinteslint-plugin
Eeslint-community
2,4 k étoiles113