npm stats
  • Search
  • About
  • Repo
  • Sponsor
  • more
    • Search
    • About
    • Repo
    • Sponsor

Made by Antonio Ramirez

eslint-plugin-unicorn

71.1.0

@sindresorhus

npmHomeRepoSnykSocket
Downloads:28252648
$ npm install eslint-plugin-unicorn
DailyWeeklyMonthlyYearly

eslint-plugin-unicorn Coverage Status npm version

Unicorn

More than 300 powerful ESLint rules

Most rules target JavaScript and TypeScript, but some also lint CSS, HTML, JSON, and Markdown 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 unopinionated configuration.
🔧 Automatically fixable by the --fix CLI option.
💡 Manually fixable by editor suggestions.
💭 Requires type information.

Name                                        Description💼🔧💡💭
better-dom-traversingPrefer better DOM traversal APIs.✅ ☑️💡
catch-error-nameEnforce a specific parameter name in catch clauses.✅🔧
class-reference-in-static-methodsEnforce consistent class references in static methods.✅💡
comment-contentEnforce better comment content.🔧
consistent-assertEnforce consistent assertion style with node:assert.✅🔧
consistent-boolean-nameEnforce consistent naming for boolean names.✅🔧💡
consistent-class-member-orderEnforce consistent class member order.✅💡
consistent-compound-wordsEnforce consistent spelling of compound words in identifiers.✅ ☑️💡
consistent-conditional-object-spreadEnforce consistent conditional object spread style.✅🔧
consistent-date-clonePrefer passing Date directly to the constructor when cloning.✅ ☑️🔧
consistent-destructuringUse destructured variables over properties.💡
consistent-empty-array-spreadPrefer consistent types when spreading a ternary in an array literal.✅🔧
consistent-existence-index-checkEnforce consistent style for element existence checks with indexOf(), lastIndexOf(), findIndex(), and findLastIndex().✅ ☑️🔧
consistent-export-decorator-positionEnforce consistent decorator position on exported classes.✅ ☑️🔧
consistent-function-scopingMove function definitions to the highest possible scope.✅
consistent-function-styleEnforce function syntax by role.💡
consistent-json-file-readEnforce consistent JSON file reads before JSON.parse().✅🔧
consistent-optional-chainingEnforce consistent optional chaining for same-base member access.✅ ☑️💡
consistent-template-literal-escapeEnforce consistent style for escaping ${ in template literals.✅🔧
consistent-tuple-labelsEnforce consistent labels on tuple type elements.✅
custom-error-definitionEnforce correct Error subclassing.🔧
default-export-styleEnforce consistent default export declarations.✅🔧💡
dom-node-datasetEnforce consistent style for DOM element dataset access.✅ ☑️🔧
empty-brace-spacesEnforce no spaces between braces.✅🔧
error-messageEnforce passing a message value when creating a built-in error.✅ ☑️
escape-caseRequire escape sequences to use uppercase or lowercase values.✅ ☑️🔧
expiring-todo-commentsAdd expiration conditions to TODO comments.✅ ☑️
explicit-length-checkEnforce explicitly comparing the length or size property of a value.✅🔧💡
explicit-timer-delayEnforce or disallow explicit delay argument for setTimeout() and setInterval().✅ ☑️🔧
filename-caseEnforce a case style for filenames and directory names.✅
id-matchRequire identifiers to match a specified regular expression.
import-styleEnforce specific import styles per module.✅ ☑️
isolated-functionsPrevent usage of variables from outside the scope of isolated functions.✅
logical-assignment-operatorsRequire or disallow logical assignment operator shorthand✅🔧💡
max-nested-callsLimit the depth of nested calls.✅
name-replacementsEnforce replacements for variable, property, and filenames.✅🔧💡
new-for-builtinsEnforce correct use of new for builtin constructors.✅ ☑️🔧💡
no-abusive-eslint-disableEnforce specifying rules to disable in eslint-disable comments.✅ ☑️
no-accessor-recursionDisallow recursive access to this within getters and setters.✅ ☑️
no-accidental-bitwise-operatorDisallow bitwise operators where a logical operator was likely intended.✅ ☑️💡
no-anonymous-default-exportDisallow anonymous functions and classes as the default export.✅ ☑️💡
no-array-callback-referencePrevent passing a function reference directly to iterator methods.✅💡
no-array-concat-in-loopDisallow array accumulation with Array#concat() in loops.✅
no-array-fill-with-reference-typeDisallow using reference values as Array#fill() values.✅ ☑️
no-array-from-fillDisallow .fill() after Array.from({length: …}).✅ ☑️
no-array-front-mutationDisallow front-of-array mutation.
no-array-method-this-argumentDisallow using the this argument in array methods.✅ ☑️🔧💡
no-array-reduceDisallow Array#reduce() and Array#reduceRight().✅🔧💡
no-array-reversePrefer Array#toReversed() over Array#reverse().✅ ☑️💡
no-array-sortPrefer Array#toSorted() over Array#sort().✅ ☑️💡
no-array-sort-for-min-maxDisallow sorting arrays to get the minimum or maximum value.✅ ☑️💡
no-array-splicePrefer Array#toSpliced() over Array#splice().✅💡
no-asterisk-prefix-in-documentation-commentsDisallow asterisk prefixes in documentation comments.🔧
no-async-promise-finallyDisallow async functions as Promise#finally() callbacks.✅ ☑️
no-await-expression-memberDisallow member access from await expression.✅🔧
no-await-in-promise-methodsDisallow using await in Promise method parameters.✅ ☑️💡
no-blob-to-fileDisallow unnecessary Blob to File conversion.✅ ☑️💡
no-boolean-sort-comparatorDisallow boolean-returning sort comparators.✅ ☑️💡
no-break-in-nested-loopDisallow break and continue in nested loops and switches inside loops.✅
no-canvas-to-imagePrefer drawing canvases directly instead of converting them to images.✅ ☑️
no-chained-comparisonDisallow chained comparisons such as a < b < c.✅ ☑️💡
no-collection-bracket-accessDisallow accessing Map, Set, WeakMap, and WeakSet entries with bracket notation.✅ ☑️💡
no-computed-property-existence-checkDisallow dynamic object property existence checks.✅💡
no-confusing-array-spliceDisallow confusing uses of Array#{splice,toSpliced}().✅💡
no-confusing-array-withDisallow confusing uses of Array#with().✅
no-console-spacesDo not use leading/trailing space between console.log parameters.✅ ☑️🔧
no-constant-zero-expressionDisallow arithmetic and bitwise operations that always evaluate to 0.✅ ☑️💡
no-declarations-before-early-exitDisallow declarations before conditional early exits when they are only used after the exit.✅ ☑️🔧
no-document-cookieDo not use document.cookie directly.✅ ☑️
no-double-comparisonDisallow two comparisons of the same operands that can be combined into one.✅ ☑️💡
no-duplicate-if-branchesDisallow duplicate adjacent branches in if chains.✅
no-duplicate-logical-operandsDisallow adjacent duplicate operands in logical expressions.✅ ☑️🔧💡
no-duplicate-loopsDisallow .map() and .filter() in for…of and for await…of loop headers.✅
no-duplicate-set-valuesDisallow duplicate values in Set constructor array literals.✅
no-empty-fileDisallow empty files.✅ ☑️
no-error-property-assignmentDisallow assigning to built-in error properties.✅ ☑️
no-exports-in-scriptsDisallow exports in scripts.✅ ☑️
no-for-eachPrefer for…of over the forEach method.✅ ☑️🔧💡
no-for-loopDo not use a for loop that can be replaced with a for-of loop.✅🔧
no-global-object-property-assignmentDisallow assigning properties on the global object.✅ ☑️
no-immediate-mutationDisallow immediate mutation after variable assignment.✅🔧💡
no-impossible-length-comparisonDisallow impossible comparisons against .length or .size.✅ ☑️
no-incorrect-query-selectorDisallow incorrect querySelector() and querySelectorAll() usage.✅🔧
no-incorrect-template-string-interpolationDisallow incorrect template literal interpolation syntax.✅💡
no-instanceof-builtinsDisallow instanceof with built-in objects✅ ☑️🔧💡
no-invalid-argument-countDisallow calling functions and constructors with an invalid number of arguments.✅ ☑️
no-invalid-character-comparisonDisallow comparing a single character from a string to a multi-character string.✅ ☑️
no-invalid-fetch-optionsDisallow invalid options in fetch() and new Request().✅ ☑️
no-invalid-file-input-acceptDisallow invalid accept values on file inputs.🔧
no-invalid-remove-event-listenerPrevent calling EventTarget#removeEventListener() with the result of an expression.✅ ☑️
no-invalid-well-known-symbol-methodsDisallow invalid implementations of well-known symbol methods.✅ ☑️🔧💡
no-keyword-prefixDisallow identifiers starting with new or class.
no-late-current-target-accessDisallow accessing event.currentTarget after the synchronous event dispatch has finished.✅
no-late-event-controlDisallow event-control method calls after the synchronous event dispatch has finished.✅
no-lonely-ifDisallow if statements as the only statement in if blocks without else.✅ ☑️🔧
no-loop-iterable-mutationDisallow mutating a loop iterable during iteration.✅
no-magic-array-flat-depthDisallow a magic number as the depth argument in Array#flat(…).✅ ☑️
no-manually-wrapped-commentsDisallow manually wrapped comments.🔧
no-mismatched-map-keyDisallow checking a Map key before accessing a different key.✅
no-misrefactored-assignmentDisallow misrefactored compound assignments where the target is duplicated in the right-hand side.✅ ☑️💡
no-named-defaultDisallow named usage of default import and export.✅ ☑️🔧
no-negated-array-predicateDisallow negated array predicate calls.✅ ☑️🔧
no-negated-comparisonDisallow negated comparisons.✅ ☑️🔧💡
no-negated-conditionDisallow negated conditions.✅ ☑️🔧
no-negation-in-equality-checkDisallow negated expression in equality check.✅ ☑️💡
no-nested-ternaryDisallow nested ternary expressions.✅🔧
no-new-arrayDisallow new Array().✅ ☑️🔧💡
no-new-bufferEnforce the use of Buffer.from() and Buffer.alloc() instead of the deprecated new Buffer().✅ ☑️🔧💡
no-non-function-verb-prefixDisallow non-function values with function-style verb prefixes.✅💭
no-nonstandard-builtin-propertiesDisallow non-standard properties on built-in objects.✅ ☑️
no-nullDisallow the use of the null literal.✅🔧💡
no-object-as-default-parameterDisallow the use of objects as default parameters.✅ ☑️
no-object-methods-with-collectionsDisallow Object methods with Map or Set.✅💡
no-optional-chaining-on-undeclared-variableDisallow optional chaining on undeclared variables.✅
no-process-exitDisallow process.exit().✅ ☑️
no-redundant-comparisonDisallow comparisons made redundant by an equality check in the same logical AND.✅ ☑️🔧💡
no-return-array-pushDisallow using the return value of Array#push() and Array#unshift().✅💡
no-selector-as-dom-nameDisallow selector syntax in DOM names.✅🔧
no-single-promise-in-promise-methodsDisallow passing single-element arrays to Promise methods.✅ ☑️🔧💡
no-static-only-classDisallow classes that only have static members.✅ ☑️🔧
no-subtraction-comparisonPrefer comparing values directly over subtracting and comparing to 0.✅ ☑️🔧💡
no-thenableDisallow then property.✅ ☑️
no-this-assignmentDisallow assigning this to a variable.✅ ☑️
no-this-outside-of-classDisallow this outside of classes.✅
no-top-level-assignment-in-functionDisallow assigning to top-level variables from inside functions.✅
no-top-level-side-effectsDisallow top-level side effects in exported modules.✅ ☑️
no-typeof-undefinedDisallow comparing undefined using typeof.✅ ☑️🔧💡
no-uncalled-methodDisallow referencing methods without calling them.✅
no-undeclared-class-membersRequire class members to be declared.✅💡
no-unnecessary-array-flat-depthDisallow using 1 as the depth argument of Array#flat().✅ ☑️🔧
no-unnecessary-array-flat-mapDisallow Array#flatMap() callbacks that only wrap a single item.✅🔧💡
no-unnecessary-array-splice-countDisallow using .length or Infinity as the deleteCount or skipCount argument of Array#{splice,toSpliced}().✅ ☑️🔧
no-unnecessary-awaitDisallow awaiting non-promise values.✅ ☑️🔧
no-unnecessary-boolean-comparisonDisallow unnecessary comparisons against boolean literals.✅🔧
no-unnecessary-fetch-optionsDisallow unnecessary options in fetch() and new Request().✅ ☑️🔧
no-unnecessary-global-thisDisallow unnecessary globalThis references.✅ ☑️🔧
no-unnecessary-nested-ternaryDisallow unnecessary nested ternary expressions.✅ ☑️🔧
no-unnecessary-polyfillsEnforce the use of built-in methods instead of unnecessary polyfills.✅ ☑️
no-unnecessary-slice-endDisallow using .length or Infinity as the end argument of {Array,String,TypedArray}#slice().✅ ☑️🔧
no-unnecessary-spliceDisallow Array#splice() when simpler alternatives exist.✅🔧
no-unreadable-array-destructuringDisallow unreadable array destructuring.✅ ☑️🔧
no-unreadable-for-of-expressionDisallow unreadable iterable expressions in for…of and for await…of loop headers.✅
no-unreadable-iifeDisallow unreadable IIFEs.✅ ☑️💡
no-unreadable-new-expressionDisallow unreadable new expressions.
no-unreadable-object-destructuringDisallow unreadable object destructuring.✅ ☑️
no-unsafe-buffer-conversionPrevent unsafe use of ArrayBuffer view .buffer.✅ ☑️💡
no-unsafe-dom-htmlDisallow unsafe DOM HTML APIs.
no-unsafe-promise-all-settled-valuesDisallow reading .value from Promise.allSettled() results without a fulfilled status guard.✅ ☑️
no-unsafe-property-keyDisallow unsafe values as property keys.✅
no-unsafe-string-replacementDisallow non-literal replacement values in String#replace() and String#replaceAll().✅
no-unused-array-method-returnDisallow ignoring the return value of selected array methods.✅ ☑️
no-unused-propertiesDisallow unused object properties.
no-useless-boolean-castDisallow unnecessary Boolean() casts in array predicate callbacks.✅ ☑️🔧
no-useless-coercionDisallow useless type coercions of values that are already of the target type.✅ ☑️🔧
no-useless-collection-argumentDisallow useless values or fallbacks in Set, Map, WeakSet, or WeakMap.✅ ☑️🔧💡
no-useless-compound-assignmentDisallow useless compound assignments such as x += 0.✅ ☑️💡
no-useless-concatDisallow useless concatenation of literals.✅ ☑️🔧
no-useless-continueDisallow useless continue statements.✅ ☑️🔧
no-useless-delete-checkDisallow unnecessary existence checks before deletion.✅ ☑️🔧💡
no-useless-elseDisallow else after a statement that exits.✅🔧
no-useless-error-capture-stack-traceDisallow unnecessary Error.captureStackTrace(…).✅ ☑️🔧
no-useless-fallback-in-spreadDisallow useless fallback when spreading in object literals.✅ ☑️🔧
no-useless-iterator-to-arrayDisallow unnecessary .toArray() on iterators.✅ ☑️🔧💡
no-useless-length-checkDisallow useless array length check.✅ ☑️🔧
no-useless-logical-operandDisallow unnecessary operands in logical expressions involving boolean literals.✅ ☑️🔧
no-useless-overrideDisallow useless overrides of class methods.✅ ☑️🔧
no-useless-promise-resolve-rejectDisallow returning/yielding Promise.resolve/reject() in async functions or promise callbacks✅ ☑️🔧
no-useless-recursionDisallow simple recursive function calls that can be replaced with a loop.✅
no-useless-spreadDisallow unnecessary spread.✅ ☑️🔧💡
no-useless-switch-caseDisallow useless case in switch statements.✅ ☑️💡
no-useless-template-literalsDisallow useless template literal expressions.✅ ☑️🔧💡
no-useless-undefinedDisallow useless undefined.✅ ☑️🔧💡
no-xor-as-exponentiationDisallow the bitwise XOR operator where exponentiation was likely intended.✅ ☑️💡
no-zero-fractionsDisallow number literals with zero fractions or dangling dots.✅ ☑️🔧
number-literal-caseEnforce proper case for numeric literals.✅ ☑️🔧
numeric-separators-styleEnforce the style of numeric separators by correctly grouping digits.✅ ☑️🔧
operator-assignmentRequire assignment operator shorthand where possible.✅🔧💡
prefer-abort-signal-anyPrefer AbortSignal.any() over manually forwarding abort events between signals.✅💡
prefer-abort-signal-timeoutPrefer AbortSignal.timeout() over manually aborting an AbortController with setTimeout().✅💡
prefer-add-event-listenerPrefer .addEventListener() and .removeEventListener() over on-functions.✅ ☑️🔧
prefer-add-event-listener-optionsPrefer an options object over a boolean in .addEventListener().✅ ☑️🔧
prefer-aggregate-errorPrefer AggregateError when throwing collected errors.✅ ☑️🔧
prefer-array-findPrefer .find(…) and .findLast(…) over the first or last element from .filter(…).✅ ☑️🔧💡
prefer-array-flatPrefer Array#flat() over legacy techniques to flatten arrays.✅ ☑️🔧
prefer-array-flat-mapPrefer .flatMap(…) over .map(…).flat() and .filter(…).flatMap(…).✅ ☑️🔧💡
prefer-array-from-asyncPrefer Array.fromAsync() over for await…of array accumulation.✅🔧
prefer-array-from-mapPrefer using the Array.from() mapping function argument.✅ ☑️🔧💡
prefer-array-from-rangePrefer Array.from({length}, …) when creating range arrays.✅ ☑️🔧
prefer-array-index-ofPrefer Array#{indexOf,lastIndexOf}() over Array#{findIndex,findLastIndex}() when looking for the index of an item.✅ ☑️🔧💡
prefer-array-iterable-methodsPrefer iterating an array directly or with Array#keys() over Array#entries() when the index or value is unused.✅🔧
prefer-array-last-methodsPrefer last-oriented array methods over Array#reverse() or Array#toReversed() followed by a method.✅ ☑️💡
prefer-array-slicePrefer Array#slice() over Array#splice() when reading from the returned array.✅💡
prefer-array-somePrefer .some(…) over .filter(…).length check and .{find,findLast,findIndex,findLastIndex}(…).✅ ☑️🔧💡
prefer-atPrefer .at() method for index access and String#charAt().✅ ☑️🔧💡
prefer-awaitPrefer await over promise chaining.✅ ☑️
prefer-bigint-literalsPrefer BigInt literals over the constructor.✅ ☑️🔧💡
prefer-blob-reading-methodsPrefer Blob#arrayBuffer() over FileReader#readAsArrayBuffer(…) and Blob#text() over FileReader#readAsText(…).✅ ☑️
prefer-block-statement-over-iifePrefer block statements over IIFEs used only for scoping.✅ ☑️🔧
prefer-boolean-returnPrefer directly returning boolean expressions over if statements.✅ ☑️🔧
prefer-class-fieldsPrefer class field declarations over this assignments in constructors.✅ ☑️🔧💡
prefer-classlist-togglePrefer using Element#classList.toggle() to toggle class names.✅ ☑️🔧💡
prefer-code-pointPrefer String#codePointAt(…) over String#charCodeAt(…) and String.fromCodePoint(…) over String.fromCharCode(…).✅ ☑️💡
prefer-continuePrefer early continues over whole-loop conditional wrapping.✅🔧
prefer-date-nowPrefer Date.now() to get the number of milliseconds since the Unix Epoch.✅ ☑️🔧
prefer-default-parametersPrefer default parameters over reassignment.✅ ☑️💡
prefer-direct-iterationPrefer direct iteration over default iterator method calls.✅ ☑️🔧
prefer-disposePrefer using using/await using over manual try/finally resource disposal.💡
prefer-dom-node-appendPrefer Element#append() over Node#appendChild().✅ ☑️🔧
prefer-dom-node-html-methodsPrefer .getHTML() and .setHTML() over .innerHTML.🔧💡
prefer-dom-node-removePrefer childNode.remove() over parentNode.removeChild(childNode).✅ ☑️🔧💡
prefer-dom-node-replace-childrenPrefer .replaceChildren() when emptying DOM children.✅ ☑️🔧
prefer-dom-node-text-contentPrefer .textContent over .innerText.✅ ☑️💡
prefer-early-returnPrefer early returns over full-function conditional wrapping.✅ ☑️🔧💡
prefer-else-ifPrefer else if over adjacent if statements with related conditions.✅🔧💡
prefer-error-is-errorPrefer Error.isError() when checking for errors.🔧
prefer-event-targetPrefer EventTarget over EventEmitter.✅ ☑️
prefer-export-fromPrefer export…from when re-exporting.✅🔧💡
prefer-flat-math-min-maxPrefer flat Math.min() and Math.max() calls over nested calls.✅ ☑️🔧
prefer-get-or-insert-computedPrefer .getOrInsertComputed() when the default value has side effects.✅🔧
prefer-global-number-constantsPrefer global numeric constants over Number static properties.✅ ☑️🔧
prefer-global-thisPrefer globalThis over window, self, and global.✅ ☑️🔧
prefer-group-byPrefer Object.groupBy() or Map.groupBy() over reduce-based grouping.✅🔧
prefer-has-checkPrefer .has() when checking existence.✅ ☑️🔧
prefer-hoisting-branch-codePrefer moving code shared by all branches of an if statement out of the branches.✅🔧💡
prefer-httpsPrefer HTTPS over HTTP.✅🔧
prefer-identifier-import-export-specifiersPrefer identifiers over string literals in import and export specifiers.✅ ☑️🔧
prefer-import-meta-propertiesPrefer import.meta.{dirname,filename} over legacy techniques for getting file paths.🔧
prefer-includesPrefer .includes() over .indexOf(), .lastIndexOf(), and Array#some() when checking for existence or non-existence.✅ ☑️🔧💡
prefer-includes-over-repeated-comparisonsPrefer .includes() over repeated equality comparisons.✅
prefer-iterable-in-constructorPrefer passing iterables directly to constructors instead of filling empty collections.✅ ☑️🔧
prefer-iterator-concatPrefer Iterator.concat(…) over temporary spread arrays.🔧💡
prefer-iterator-helpersPrefer iterator helpers over temporary arrays from iterators.✅ ☑️💡
prefer-iterator-to-arrayPrefer Iterator#toArray() over temporary arrays from iterator spreads.✅🔧💡
prefer-iterator-to-array-at-endPrefer moving .toArray() to the end of iterator helper chains.✅ ☑️💡
prefer-keyboard-event-keyPrefer KeyboardEvent#key over deprecated keyboard event properties.✅ ☑️🔧💡
prefer-location-assignPrefer location.assign() over assigning to location.href.✅🔧
prefer-logical-operator-over-ternaryPrefer using a logical operator over a ternary.