eslint-plugin-unicorn

repository·main·Indexed 26 days ago

https://github.com/sindresorhus/eslint-plugin-unicorn

An ESLint plugin providing more than 300 rules primarily targeting JavaScript and TypeScript, with additional support for CSS, HTML, JSON, and Markdown. It offers recommended and unopinionated configurations to improve code quality, consistency, and the use of modern APIs. The plugin supports ESLint flat config and requires ESLint >=10.4 and ESM.

Tokens
169.1K
Snippets
455
Records
719
Agent score
89%

What's inside eslint-plugin-unicorn

  1. Understand rule configuration and fixability in eslint-plugin-unicorn

    main

    Rules in eslint-plugin-unicorn are categorized by their configuration settings and how they can be resolved:

    • Configurations: Rules are available in the recommended and unopinionated configurations.
    • Automatic Fixes: Many rules are automatically fixable using the ESLint --fix CLI option.
    • Manual Fixes: Some rules provide editor suggestions for manual fixing.
    • Type Information: Certain rules require TypeScript type information to function correctly.
  2. Use the `prefer-observer-apis` rule

    main

    The prefer-observer-apis rule encourages using ResizeObserver and IntersectionObserver instead of resize and scroll event listeners that perform synchronous layout or viewport geometry reads.

    This rule is enabled by default in the recommended configuration but is disabled in the unopinionated configuration.

    Note: The rule only reports listeners that perform layout or viewport geometry reads. Plain scroll position listeners (e.g., reading window.scrollY) are ignored because an observer API is not always a superior replacement in those cases.

  3. Use the `prefer-else-if` rule

    main

    The prefer-else-if rule enforces the use of else if instead of adjacent, independent if statements when they compare the same identifier or static member expression against mutually exclusive static values. This makes control flow explicit and prevents unnecessary evaluation of subsequent conditions once a match is found.

    Configuration Status

    • Enabled in the recommended config.
    • Disabled in the unopinionated config.

    Autofixing

    This rule is automatically fixable using the ESLint --fix CLI option. However, autofixing is limited to normalized plain identifier discriminants where previous branches and later conditions have no side effects. For other cases, the rule provides manual suggestions to avoid changing behavior if state changes between checks.

    // ❌
    if (foo === 1) {
    	one();
    }
    
    if (foo === 2) {
    	two();
    }
    
    // ✅
    if (foo === 1) {
    	one();
    } else if (foo === 2) {
    	two();
    }
  4. Use the `prefer-array-index-of` rule

    main

    The prefer-array-index-of rule encourages using Array#indexOf() or Array#lastIndexOf() instead of Array#findIndex() or Array#findLastIndex() when searching for a simple item.

    Use indexOf/lastIndexOf when you are looking for a literal, a variable, or an expression without side effects. Continue using findIndex/findLastIndex if the search expression is complex, relies on arguments/context, or contains side effects.

    This rule is enabled in the recommended and unopinionated configurations. It is automatically fixable using the ESLint --fix option.

  5. Use the `prefer-temporal` rule to replace `Date` with `Temporal`

    main

    The prefer-temporal rule encourages the use of the modern Temporal API instead of the legacy Date object. Temporal provides immutable types (like Temporal.Instant, Temporal.PlainDate, and Temporal.ZonedDateTime) that avoid common Date issues such as zero-indexed months and unreliable string parsing.

    This rule is automatically fixable via the --fix CLI option for Date.now() and certain new Date() constructors. Other cases (like string parsing) are reported as suggestions because the correct Temporal type depends on the specific use case.

    Note: Temporal is part of ECMAScript 2026. For older environments, use @js-temporal/polyfill.

    // ❌ — the current moment
    const now = new Date();
    
    // ✅
    const now = Temporal.Now.instant();
  6. Use the `prefer-array-last-methods` rule

    main

    The prefer-array-last-methods rule encourages using last-oriented array methods (like findLast or reduceRight) instead of reversing an array with .reverse() or .toReversed() and then calling a forward method. This improves readability by expressing the traversal direction directly and avoids unnecessary array reversal steps.

    This rule is included in the recommended and unopinionated configurations.

    Note: This rule only provides editor suggestions and is not automatically fixable via ESLint's --fix flag. Because replacements can change observable behavior regarding mutation, sparse arrays, or callback arguments, you must manually review and apply the suggested changes.

  7. Use the `prefer-promise-try` rule

    main

    The prefer-promise-try rule encourages using Promise.try() instead of older promise-wrapping boilerplate. Promise.try() is the standard way to run a callback that may return a value, return a promise, or throw synchronously, ensuring the result is always a promise.

    Configuration Status:

    • Enabled in the recommended config.
    • Disabled in the unopinionated config.

    Autofixing: This rule is automatically fixable using the ESLint --fix CLI option, but only for the new Promise(resolve => resolve(fn())) pattern where the timing remains synchronous. The rule will not automatically fix Promise.resolve().then(fn) because replacing it with Promise.try(fn) changes the execution timing and argument passing behavior.

  8. Use the `prefer-modern-dom-apis` rule

    main

    The prefer-modern-dom-apis rule enforces the use of modern DOM APIs over older, more verbose alternatives. This rule is enabled by default in the recommended and unopinionated configurations. It is automatically fixable using the ESLint --fix option.

    Advantages of modern APIs:

    • No need to traverse to the parent node.
    • Ability to append multiple nodes at once.
    • Removing all child nodes without manual iteration.
    • Support for both DOMString and DOM node objects.

    Note on Autofix: The autofix assumes your code does not rely on specific MutationObserver records generated by repeated removals.

  9. Use the no-unreadable-iife rule

    main

    The no-unreadable-iife rule disallows Immediately Invoked Function Expressions (IIFEs) that use parenthesized arrow function bodies. Such patterns are considered unreadable because the parentheses make the IIFE look like a grouped expression, obscuring the start of the function body.

    This rule is included in the following configurations:

    • recommended (enabled)
    • unopinionated (enabled)

    This rule is manually fixable via editor suggestions.

  10. Use the `no-uncalled-method` rule

    main

    The no-uncalled-method rule disallows referencing methods without calling them. Forgetting to call a method often results in returning the function itself instead of the intended value, which is typically a bug in assignments, return statements, or conditional logic.

    This rule targets known Array and String methods. It identifies potential targets through:

    • Syntax analysis
    • Type annotations
    • Parser type information
    • Conventional variable names (e.g., array, string)
    • const aliases of those names

    To avoid false positives, the rule ignores receivers that it cannot identify.