# Oxc > url: /docs/guide/usage/linter/rules/eslint/accessor-pairs.md --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/accessor-pairs.md --- url: /docs/guide/usage/linter/rules/eslint/accessor-pairs.md --- ### What it does Enforces getter/setter pairs in objects and classes. ### Why is this bad? It's a common mistake in JavaScript to create an object with just a setter for a property but never have a corresponding getter defined for it. Without a getter, you cannot read the property, so it ends up not being used. ### Examples Examples of **incorrect** code for this rule: ```js var o = { set a(value) { this.val = value; }, }; class C { set a(value) { this.val = value; } } ``` Examples of **correct** code for this rule: ```js var o = { set a(value) { this.val = value; }, get a() { return this.val; }, }; class C { set a(value) { this.val = value; } get a() { return this.val; } } ``` ## Configuration This rule accepts a configuration object with the following properties: ### enforceForClassMembers type: `boolean` default: `true` Enforce the rule for class members. ### enforceForTSTypes type: `boolean` default: `false` Enforce the rule for TypeScript interfaces and types. ### getWithoutSet type: `boolean` default: `false` Report a getter without a setter. ### setWithoutGet type: `boolean` default: `true` Report a setter without a getter. ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "accessor-pairs": "error" } } ``` ```bash [CLI] oxlint --deny accessor-pairs ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/contribute/linter/adding-rules.md --- url: /docs/contribute/linter/adding-rules.md --- # Adding Linter Rules The best and easiest way to contribute to Oxlint is by adding new linter rules. This guide will walk you through this process, using ESLint's [`no-debugger`](https://eslint.org/docs/latest/rules/no-debugger) rule as an example. :::tip Make sure you've read the [setup instructions](../development.md) first. ::: ## Step 1: Pick a Rule Our [Linter product plan and progress](https://github.com/oxc-project/oxc/issues/481) issue tracks the status of all rules we want to implement from existing ESLint plugins. From there, pick a plugin that looks interesting to you and find a rule that has not been implemented. **Important**: Since ESLint-compatible JavaScript plugin support is now available, we do not plan to add new Rust-based plugins. However, contributions that add rules to existing plugins are **highly encouraged**. If you think a rule or plugin would benefit from being written in rust, please open a discussion first, before making a pull request. Most documentation pages for ESLint rules include a link to the rule's [source code](https://eslint.org/docs/latest/rules/no-debugger#resources). Using this as a reference will help you with your implementation. ## Step 2: Rule Generation Next, run the rulegen script to generate boilerplate code for your new rule. ```bash just new-rule no-debugger ``` This will: 1. Create a new file in `crates/oxc_linter/src/rules//.rs` with the start of your rule's implementation and all test cases ported from ESLint 2. Register the rule in the appropriate `mod` in [`rules.rs`](https://github.com/oxc-project/oxc/blob/main/crates/oxc_linter/src/rules.rs) 3. Add the rule to `oxc_macros::declare_all_lint_rules!` For rules that are part of a different plugin, you'll need to use that plugin's own rulegen script. :::tip Run `just` with no arguments to see all available commands. ::: ```bash just new-rule [name] # for eslint core rules just new-jest-rule [name] # for eslint-plugin-jest just new-ts-rule [name] # for @typescript-eslint/eslint-plugin just new-unicorn-rule [name] # for eslint-plugin-unicorn just new-import-rule [name] # for eslint-plugin-import just new-react-rule [name] # for eslint-plugin-react and eslint-plugin-react-hooks just new-jsx-a11y-rule [name] # for eslint-plugin-jsx-a11y just new-oxc-rule [name] # for oxc's own rules just new-nextjs-rule [name] # for eslint-plugin-next just new-jsdoc-rule [name] # for eslint-plugin-jsdoc just new-react-perf-rule [name] # for eslint-plugin-react-perf just new-n-rule [name] # for eslint-plugin-n just new-promise-rule [name] # for eslint-plugin-promise just new-vitest-rule [name] # for eslint-plugin-vitest ``` The generated file will look something like this: ::: code-group ````rust [rules/eslint/no_debugger.rs] use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::Span; use crate::{ context::LintContext, fixer::{RuleFix, RuleFixer}, rule::Rule, AstNode, }; #[derive(Debug, Default, Clone)] pub struct NoDebugger; declare_oxc_lint!( /// ### What it does /// /// /// ### Why is this bad? /// /// /// ### Examples /// /// Examples of **incorrect** code for this rule: /// ```js /// FIXME: Tests will fail if examples are missing or syntactically incorrect. /// ``` /// /// Examples of **correct** code for this rule: /// ```js /// FIXME: Tests will fail if examples are missing or syntactically incorrect. /// ``` NoDebugger, nursery, // TODO: change category to `correctness`, `suspicious`, `pedantic`, `perf`, `restriction`, or `style` // See for details pending // TODO: describe fix capabilities. Remove if no fix can be done, // keep at 'pending' if you think one could be added but don't know how. // Options are 'fix', 'fix_dangerous', 'suggestion', and 'conditional_fix_suggestion' ); impl Rule for NoDebugger { fn run<'a>(&self, node: &AstNode<'a>, ctx: &LintContext<'a>) {} } #[test] fn test() { use crate::tester::Tester; let pass = vec!["var test = { debugger: 1 }; test.debugger;"]; let fail = vec!["if (foo) debugger"]; Tester::new(NoDebugger::NAME, pass, fail).test_and_snapshot(); } ```` ::: Your rule should now be ready to run! You can try it out with `cargo test -p oxc_linter`. The tests should fail, since you haven't implemented the rule yet. ## Step 3: Fill Out the Template ### Documentation Fill out the various documentation sections. * Provide a clear and concise summary of what the rule does. * Explain why the rule is important and what undesirable behavior it prevents. * Provide examples of code that violates the rule and code that does not. Remember, we use this documentation to generate the [rule documentation pages](/docs/guide/usage/linter/rules) for this website, so make sure your documentation is clear and helpful! #### Configuration Documentation If your rule has configuration options, you will need to document them. You should do so via the system for auto-generating documentation. This should be partially generated for you automatically by the rulegen script. Each configuration option should be defined by adding fields to the rule's struct: ```rust pub struct RuleName { option_name: bool, another_option: String, yet_another_option: Vec, } ``` Alternatively, you can instead define a separate `Config` struct to hold all configuration options: ```rust pub struct RuleName(Box); pub struct RuleNameConfig { option_name: bool, } ``` The configuration options should have `JsonSchema` derived for them and also a serde decoration, like so: ```rust use schemars::JsonSchema; #[derive(Debug, Default, Clone, JsonSchema)] #[serde(rename_all = "camelCase", default)] pub struct RuleName { option_name: bool, } ``` Add documentation comments (`///`) to each field to describe the option, for example: ```rust use schemars::JsonSchema; #[derive(Debug, Default, Clone, JsonSchema)] #[serde(rename_all = "camelCase", default)] pub struct RuleName { /// Whether to check for foo and bar when evaluating baz. /// The comment can be as long as you need to fully describe the option. option_name: bool, } ``` The default value and the type of each option will be automatically extracted from the struct definition, and should not be mentioned in the documentation comments. See [this issue](https://github.com/oxc-project/oxc/issues/14743) for dozens of examples of how to properly document configuration options in all kinds of rules. You can view the generated documentation by running `cargo run -p website -- linter-rules --rule-docs target/rule-docs --git-ref $(git rev-parse HEAD)` and then opening `target/rule-docs//.md`. ### Rule Category First, pick a [rule category](../linter.md#rule-category) that best fits the rule. Remember that `correctness` rules will be run by default, so be careful when choosing this category. Set your category within the `declare_oxc_lint!` macro. ### Fixer Status If the rule has a fixer, register what kind of fixes it provides within `declare_oxc_lint!`. If you're not comfortable with implementing a fixer, you can also use `pending` as a placeholder. This helps other contributors find and implement missing fixers down the line. ### Diagnostics Create a function to create diagnostics for rule violations. Follow these principles: 1. The `message` should be an imperative statement about what is wrong, not a description of what the rule does. 2. The `help` message should be a command-like statement that tells the user how to fix the issue. ::: code-group ```rust [good] fn no_debugger_diagnostic(span: Span) -> OxcDiagnostic { OxcDiagnostic::warn("`debugger` statement is not allowed") .with_help("Remove this `debugger` statement") .with_label(span) } ``` ```rust [bad] fn no_debugger_diagnostic(span: Span) -> OxcDiagnostic { OxcDiagnostic::warn("Disallow `debugger` statements") .with_help("`debugger` statements are not allowed.") .with_label(span) ``` ::: ## Step 4: Rule Implementation Read the rule's source code to understand how it works. Although Oxlint works similarly to ESLint, it is unlikely that the rule can be ported directly. ESLint rules have a `create` function that returns an object whose keys are AST nodes that trigger the rule and values are functions that run lints on those nodes. Oxlint rules run on one of a few triggers, each of which come from the [`Rule`](https://github.com/oxc-project/oxc/blob/main/crates/oxc_linter/src/rule.rs) trait: 1. Run on each AST node (via `run`) 2. Run on each symbol (via `run_on_symbol`) 3. Run a single time on the entire file (via `run_once`) In the case of `no-debugger`, we are looking for `DebuggerStatement` nodes, so we'll use `run`. Here's a simplified version of the rule: ::: code-group ````rust [rules/eslint/no_debugger.rs] use oxc_ast::AstKind; use oxc_diagnostics::OxcDiagnostic; use oxc_macros::declare_oxc_lint; use oxc_span::Span; use crate::{context::LintContext, rule::Rule, AstNode}; fn no_debugger_diagnostic(span: Span) -> OxcDiagnostic { OxcDiagnostic::warn("`debugger` statement is not allowed") .with_label(span) } #[derive(Debug, Default, Clone)] pub struct NoDebugger; declare_oxc_lint!( /// ### What it does /// Checks for usage of the `debugger` statement /// /// ### Why is this bad? /// `debugger` statements do not affect functionality when a /// debugger isn't attached. They're most commonly an /// accidental debugging leftover. /// /// ### Example /// /// Examples of **incorrect** code for this rule: /// ```js /// async function main() { /// const data = await getData(); /// const result = complexCalculation(data); /// debugger; /// } /// ``` NoDebugger, correctness ); impl Rule for NoDebugger { // Runs on each node in the AST fn run<'a>(&self, node: &AstNode<'a>, ctx: &LintContext<'a>) { // `debugger` statements have their own AST kind if let AstKind::DebuggerStatement(stmt) = node.kind() { // Report a violation ctx.diagnostic(no_debugger_diagnostic(stmt.span)); } } } ```` ::: :::tip You will want to get familiar with the data stored in [`Semantic`](https://github.com/oxc-project/oxc/blob/main/crates/oxc_semantic/src/lib.rs#L59), which is where all data extracted during semantic analysis is stored. You will also want to familiarize yourself with the AST structure. The two most important data structures here are [`AstNode`](https://github.com/oxc-project/oxc/blob/main/crates/oxc_semantic/src/node/mod.rs) and [`AstKind`](https://github.com/oxc-project/oxc/blob/main/crates/oxc_ast/src/generated/ast_kind.rs) ::: ## Step 5: Testing To test your rule whenever you make a change, run: ```bash just watch "test -p oxc_linter -- rule-name" ``` Or to just test it once, run: ```bash cargo test -p oxc_linter -- rule-name # Or cargo insta test -p oxc_linter -- rule-name ``` Oxlint uses [`cargo insta`](https://insta.rs/docs) for snapshot testing. `cargo test` will fail if snapshots have changed or have just been created. You can run `cargo insta test -p oxc_linter` to not see diffs in your test results. You can review the snapshots by running `cargo insta review`, or skip the review and just accept all changes using `cargo insta accept`. When you are ready to submit your PR, run `just ready` or `just r` to run CI checks locally. You can also run `just fix` to auto-fix any lint, format, or typo problems. Once `just ready` is passing, create a PR and a maintainer will review your changes. ## General Advice ### Pin point the error message to the shortest code span We want the user to focus on the problematic code rather than deciphering the error message to identify which part of the code is erroneous. ### Use `let-else` statements If you find yourself deeply nesting [`if-let`](https://doc.rust-lang.org/rust-by-example/flow_control/if_let.html) statements, consider using [`let-else`](https://doc.rust-lang.org/rust-by-example/flow_control/let_else.html) instead. :::tip CodeAesthetic's [never-nesting video](https://www.youtube.com/watch?v=CFRhGnuXG-4) explains this concept in more detail. ::: ::: code-group ```rust [good] // let-else is easier to read fn run<'a>(&self, node: &AstNode<'a>, ctx: &LintContext<'a>) { let AstKind::JSXOpeningElement(jsx_opening_elem) = node.kind() else { return; }; let Some(expr) = container.expression.as_expression() else { return; }; let Expression::BooleanLiteral(expr) = expr.without_parenthesized() else { return; }; // ... } ``` ```rust [bad] // deep nesting is hard to read fn run<'a>(&self, node: &AstNode<'a>, ctx: &LintContext<'a>) { if let AstKind::JSXOpeningElement(jsx_opening_elem) = node.kind() { if let Some(expr) = container.expression.as_expression() { if let Expression::BooleanLiteral(expr) = expr.without_parenthesized() { // ... } } } } ``` ::: ### Use `CompactStr` where possible Reducing allocations as much as possible is critical for performance in `oxc`. The `String` type requires allocating memory on the heap, which costs memory and CPU cycles. It is possible to [store small strings inline](https://oxc.rs/docs/learn/performance.html#string-inlining) (up to 24 bytes on 64-bit systems) on the stack using `CompactStr`, which means we don't need to allocate memory. If the string is too large to store inline, it will allocate the necessary space. Using `CompactStr` can be used almost anywhere that has the type `String` or `&str`, and can save a significant amount memory and CPU cycles compared to the `String` type. ::: code-group ```rust [good] struct Element { name: CompactStr } let element = Element { name: "div".into() }; ``` ```rust [bad] struct Element { name: String } let element = Element { name: "div".to_string() }; ``` ::: --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/typescript/adjacent-overload-signatures.md ## What it does Require that function overload signatures be consecutive. ## Why is this bad? Function overload signatures represent multiple ways a function can be called, potentially with different return types. It's typical for an interface or type alias describing a function to place all overload signatures next to each other. If Signatures placed elsewhere in the type are easier to be missed by future developers reading the code. ## Examples Examples of **incorrect** code for this rule: ```typescript declare namespace Foo { export function foo(s: string): void; export function foo(n: number): void; export function bar(): void; export function foo(sn: string | number): void; } type Foo = { foo(s: string): void; foo(n: number): void; bar(): void; foo(sn: string | number): void; }; interface Foo { foo(s: string): void; foo(n: number): void; bar(): void; foo(sn: string | number): void; } class Foo { foo(s: string): void; foo(n: number): void; bar(): void {} foo(sn: string | number): void {} } export function foo(s: string): void; export function foo(n: number): void; export function bar(): void; export function foo(sn: string | number): void; ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "typescript/adjacent-overload-signatures": "error" } } ``` ```bash [CLI] oxlint --deny typescript/adjacent-overload-signatures ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/jsx_a11y/alt-text.md --- url: /docs/guide/usage/linter/rules/jsx_a11y/alt-text.md --- ### What it does Enforce that all elements that require alternative text have meaningful information to relay back to the end user. ### Why is this bad? Alternative text is a critical component of accessibility for screen reader users, enabling them to understand the content and function of an element. Missing or inadequate alt text makes content inaccessible to users who rely on assistive technologies. ### Examples Examples of **incorrect** code for this rule: ```jsx ``` Examples of **correct** code for this rule: ```jsx A close-up of a white daisy Navigation link ``` ## Configuration This rule accepts a configuration object with the following properties: ### area type: `string[]` default: `[]` Custom components to check for alt text on `area` elements. ### img type: `string[]` default: `[]` Custom components to check for alt text on `img` elements. ### input\[type="image"] type: `string[]` default: `[]` Custom components to check for alt text on `input[type="image"]` elements. ### object type: `string[]` default: `[]` Custom components to check for alt text on `object` elements. ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["jsx-a11y"], "rules": { "jsx-a11y/alt-text": "error" } } ``` ```bash [CLI] oxlint --deny jsx-a11y/alt-text --jsx-a11y-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/promise/always-return.md --- url: /docs/guide/usage/linter/rules/promise/always-return.md --- ### What it does Require returning inside each `then()` to create readable and reusable Promise chains. We also allow someone to throw inside a `then()` which is essentially the same as return `Promise.reject()`. ### Why is this bad? Broken Promise Chain. Inside the first `then()` callback, a function is called but not returned. This causes the next `then()` in the chain to execute immediately without waiting for the called function to complete. ### Examples Examples of **incorrect** code for this rule: ```javascript myPromise.then(function (val) {}); myPromise.then(() => { doSomething(); }); myPromise.then((b) => { if (b) { return "yes"; } else { forgotToReturn(); } }); ``` Examples of **correct** code for this rule: ```javascript myPromise.then((val) => val * 2); myPromise.then(function (val) { return val * 2; }); myPromise.then(doSomething); // could be either myPromise.then((b) => { if (b) { return "yes"; } else { return "no"; } }); ``` ## Configuration This rule accepts a configuration object with the following properties: ### ignoreAssignmentVariable type: `string[]` default: `["globalThis"]` You can pass an `{ ignoreAssignmentVariable: [] }` as an option to this rule with a list of variable names so that the last `then()` callback in a promise chain does not warn if it does an assignment to a global variable. Default is `["globalThis"]`. ```javascript /* promise/always-return: ["error", { ignoreAssignmentVariable: ["globalThis"] }] */ // OK promise.then((x) => { globalThis = x; }); promise.then((x) => { globalThis.x = x; }); // OK promise.then((x) => { globalThis.x.y = x; }); // NG promise.then((x) => { anyOtherVariable = x; }); // NG promise.then((x) => { anyOtherVariable.x = x; }); // NG promise.then((x) => { x(); }); ``` ### ignoreLastCallback type: `boolean` default: `false` You can pass an `{ ignoreLastCallback: true }` as an option to this rule so that the last `then()` callback in a promise chain does not warn if it does not have a `return`. Default is `false`. ```javascript // OK promise.then((x) => { console.log(x); }); // OK void promise.then((x) => { console.log(x); }); // OK await promise.then((x) => { console.log(x); }); promise // NG .then((x) => { console.log(x); }) // OK .then((x) => { console.log(x); }); // NG const v = promise.then((x) => { console.log(x); }); // NG const v = await promise.then((x) => { console.log(x); }); function foo() { // NG return promise.then((x) => { console.log(x); }); } ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["promise"], "rules": { "promise/always-return": "error" } } ``` ```bash [CLI] oxlint --deny promise/always-return --promise-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/jsx_a11y/anchor-ambiguous-text.md --- url: /docs/guide/usage/linter/rules/jsx_a11y/anchor-ambiguous-text.md --- ### What it does Inspects anchor link text for the use of ambiguous words. This rule checks the text from the anchor element `aria-label` if available. In absence of an anchor `aria-label` it combines the following text of it's children: * `aria-label` if available * if the child is an image, the `alt` text * the text content of the HTML element ### Why is this bad? Screen readers users rely on link text for context, ambiguous words such as "click here" do not provide enough context. ### Examples Examples of **incorrect** code for this rule: ```jsx link click here ``` Examples of **correct** code for this rule: ```jsx read this tutorial click here ``` ## Configuration This rule accepts a configuration object with the following properties: ### words type: `string[]` default: `["click here", "here", "link", "a link", "learn more"]` List of ambiguous words or phrases that should be flagged in anchor text. ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["jsx-a11y"], "rules": { "jsx-a11y/anchor-ambiguous-text": "error" } } ``` ```bash [CLI] oxlint --deny jsx-a11y/anchor-ambiguous-text --jsx-a11y-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/jsx_a11y/anchor-has-content.md --- url: /docs/guide/usage/linter/rules/jsx_a11y/anchor-has-content.md --- ### What it does Enforce that anchors have content and that the content is accessible to screen readers. Accessible means that it is not hidden using the `aria-hidden` prop. Alternatively, you may use the `title` prop or the `aria-label` prop. ### Why is this bad? Anchor elements without content can be confusing for users relying on screen readers to understand. ### Examples Examples of **correct** code for this rule: ```jsx Anchor Content! ``` Examples of **incorrect** code for this rule: ```jsx ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["jsx-a11y"], "rules": { "jsx-a11y/anchor-has-content": "error" } } ``` ```bash [CLI] oxlint --deny jsx-a11y/anchor-has-content --jsx-a11y-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/jsx_a11y/anchor-is-valid.md --- url: /docs/guide/usage/linter/rules/jsx_a11y/anchor-is-valid.md --- ### What it does The HTML `` element, with a valid href attribute, is formally defined as representing a **hyperlink**. That is, a link between one HTML document and another, or between one location inside an HTML document and another location inside the same document. While before it was possible to attach logic to an anchor element, with the advent of JSX libraries, it's now easier to attach logic to any HTML element, anchors included. This rule is designed to prevent users to attach logic at the click of anchors, and also makes sure that the `href` provided to the anchor element is valid. If the anchor has logic attached to it, the rules suggests to turn it to a `button`, because that's likely what the user wants. Anchor `` elements should be used for navigation, while `` should be used for user interaction. Consider the following: ```jsx <> Perform action Perform action Perform action ``` All these anchor implementations indicate that the element is only used to execute JavaScript code. All the above should be replaced with: ```jsx ``` ### Why is this bad? There are **many reasons** why an anchor should not have logic and have a correct `href` attribute: * it can disrupt the correct flow of the user navigation e.g. a user that wants to open the link in another tab, but the default "click" behaviour is prevented * it can source of invalid links, and crawlers can't navigate the website, risking to penalise SEO ranking ### Examples Examples of **valid** code for this rule: ```jsx <> navigate here navigate here navigate here ``` Examples of **invalid** code for this rule: ```jsx <> navigate here navigate here navigate here navigate here navigate here ``` ### Reference * [WCAG 2.1.1](https://www.w3.org/WAI/WCAG21/Understanding/keyboard) ## Configuration This rule accepts a configuration object with the following properties: ### validHrefs type: `string[]` default: `[]` List of strings that are valid href values. ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["jsx-a11y"], "rules": { "jsx-a11y/anchor-is-valid": "error" } } ``` ```bash [CLI] oxlint --deny jsx-a11y/anchor-is-valid --jsx-a11y-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/oxc/approx-constant.md --- url: /docs/guide/usage/linter/rules/oxc/approx-constant.md --- ### What it does Disallows the use of approximate constants, instead preferring the use of the constants in the `Math` object. ### Why is this bad? Approximate constants are not as accurate as the constants in the `Math` object. Using the `Math` constants improves code readability and accuracy. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/Math for more information. ### Examples Examples of **incorrect** code for this rule: ```javascript let log10e = 0.434294; ``` Examples of **correct** code for this rule: ```javascript let log10e = Math.LOG10E; ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "oxc/approx-constant": "error" } } ``` ```bash [CLI] oxlint --deny oxc/approx-constant ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/jsx_a11y/aria-activedescendant-has-tabindex.md --- url: /docs/guide/usage/linter/rules/jsx_a11y/aria-activedescendant-has-tabindex.md --- ### What it does Enforce elements with aria-activedescendant are tabbable. ### Why is this bad? Elements with `aria-activedescendant` must be tabbable for users to navigate to them using keyboard input. Without proper tabindex, screen reader users cannot access the element through keyboard navigation, making the functionality inaccessible. ### Examples Examples of **incorrect** code for this rule: ```jsx const Bad =
; ``` Examples of **correct** code for this rule: ```jsx const Good = ( <>
); ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["jsx-a11y"], "rules": { "jsx-a11y/aria-activedescendant-has-tabindex": "error" } } ``` ```bash [CLI] oxlint --deny jsx-a11y/aria-activedescendant-has-tabindex --jsx-a11y-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/jsx_a11y/aria-props.md --- url: /docs/guide/usage/linter/rules/jsx_a11y/aria-props.md --- ### What it does Enforces that elements do not use invalid ARIA attributes. ### Why is this bad? Using invalid ARIA attributes can mislead screen readers and other assistive technologies. It may cause the accessibility features of the website to fail, making it difficult for users with disabilities to use the site effectively. This rule includes fixes for some common typos. ### Examples Examples of **incorrect** code for this rule: ```jsx ``` Examples of **correct** code for this rule: ```jsx ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["jsx-a11y"], "rules": { "jsx-a11y/aria-props": "error" } } ``` ```bash [CLI] oxlint --deny jsx-a11y/aria-props --jsx-a11y-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/jsx_a11y/aria-proptypes.md --- url: /docs/guide/usage/linter/rules/jsx_a11y/aria-proptypes.md --- ### What it does Enforces that elements do not use invalid ARIA state and property values. ### Why is this bad? Using invalid ARIA state and property values can mislead screen readers and other assistive technologies. It may cause the accessibility features of the website to fail, making it difficult for users with disabilities to use the site effectively. ### Examples Examples of **incorrect** code for this rule: ```jsx
``` Examples of **correct** code for this rule: ```jsx
``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["jsx-a11y"], "rules": { "jsx-a11y/aria-proptypes": "error" } } ``` ```bash [CLI] oxlint --deny jsx-a11y/aria-proptypes --jsx-a11y-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/jsx_a11y/aria-role.md --- url: /docs/guide/usage/linter/rules/jsx_a11y/aria-role.md --- ### What it does Elements with ARIA roles must use a valid, non-abstract ARIA role. A reference to role definitions can be found at [WAI-ARIA](https://www.w3.org/TR/wai-aria/#role_definitions) site. ### Why is this bad? The intent of this Success Criterion is to ensure that Assistive Technologies (AT) can gather information about, activate (or set) and keep up to date on the status of user interface controls in the content(such as screen readers, screen magnifiers, and speech recognition software, used by people with disabilities). When standard controls from accessible technologies are used, this process is straightforward. If the user interface elements are used according to specification the conditions of this provision will be met. If custom controls are created, however, or interface elements are programmed (in code or script) to have a different role and/or function than usual, then additional measures need to be taken to ensure that the controls provide important information to assistive technologies and allow themselves to be controlled by assistive technologies. A particularly important state of a user interface control is whether or not it has focus. The focus state of a control can be programmatically determined, and notifications about change of focus are sent to user agents and assistive technology. Other examples of user interface control state are whether or not a checkbox or radio button has been selected, or whether or not a collapsible tree or list node is expanded or collapsed. ### Examples Examples of **incorrect** code for this rule: ```jsx
``` Examples of **correct** code for this rule: ```jsx
``` ## Configuration This rule accepts a configuration object with the following properties: ### allowedInvalidRoles type: `string[]` default: `[]` Custom roles that should be allowed in addition to the ARIA spec. ### ignoreNonDOM type: `boolean` default: `false` Determines if developer-created components are checked. ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["jsx-a11y"], "rules": { "jsx-a11y/aria-role": "error" } } ``` ```bash [CLI] oxlint --deny jsx-a11y/aria-role --jsx-a11y-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/jsx_a11y/aria-unsupported-elements.md --- url: /docs/guide/usage/linter/rules/jsx_a11y/aria-unsupported-elements.md --- ### What it does Enforces that reserved DOM elements do not contain ARIA roles, states, or properties. ### Why is this bad? Certain reserved DOM elements do not support ARIA roles, states and properties. This is often because they are not visible, for example `meta`, `html`, `script`, `style`. Adding ARIA attributes to these elements is meaningless and can create confusion for screen readers. ### Examples Examples of **incorrect** code for this rule: ```jsx ``` Examples of **correct** code for this rule: ```jsx ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["jsx-a11y"], "rules": { "jsx-a11y/aria-unsupported-elements": "error" } } ``` ```bash [CLI] oxlint --deny jsx-a11y/aria-unsupported-elements --jsx-a11y-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/array-callback-return.md --- url: /docs/guide/usage/linter/rules/eslint/array-callback-return.md --- ### What it does Enforce return statements in callbacks of array methods ### Why is this bad? Array has several methods for filtering, mapping, and folding. If we forget to write return statement in a callback of those, it’s probably a mistake. If you don’t want to use a return or don’t need the returned results, consider using .forEach instead. ### Examples Examples of **incorrect** code for this rule: ```javascript let foo = [1, 2, 3, 4]; foo.map((a) => { console.log(a); }); ``` Examples of **correct** code for this rule: ```javascript let foo = [1, 2, 3, 4]; foo.map((a) => { console.log(a); return a; }); ``` ## Configuration This rule accepts a configuration object with the following properties: ### allowImplicit type: `boolean` default: `false` When set to true, allows callbacks of methods that require a return value to implicitly return undefined with a return statement containing no expression. ### checkForEach type: `boolean` default: `false` When set to true, rule will also report forEach callbacks that return a value. ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "array-callback-return": "error" } } ``` ```bash [CLI] oxlint --deny array-callback-return ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/typescript/array-type.md ## What it does Require consistently using either `T[]` or `Array` for arrays. ## Why is this bad? Using the `Array` type directly is not idiomatic. Instead, use the array type `T[]` or `Array`. ## Examples Examples of **incorrect** code for this rule: ```typescript /*oxlint array-type: ["error", { "default": "array" }] */ const arr: Array = new Array(); ``` ```typescript /*oxlint array-type: ["error", { "default": "generic" }] */ const arr: number[] = new Array(); ``` ```typescript /*oxlint array-type: ["error", { "default": "array-simple" }] */ const a: (string | number)[] = ["a", "b"]; const b: { prop: string }[] = [{ prop: "a" }]; const c: Array = ["a", "b"]; const d: Array = ["a", "b"]; ``` Examples of **correct** code for this rule: ```typescript /*oxlint array-type: ["error", { "default": "array" }] */ const arr: number[] = new Array(); ``` ```typescript /*oxlint array-type: ["error", { "default": "generic" }] */ const arr: Array = new Array(); ``` ```typescript /*oxlint array-type: ["error", { "default": "array-simple" }] */ const a: Array = ["a", "b"]; const b: Array<{ prop: string }> = [{ prop: "a" }]; const c: string[] = ["a", "b"]; const d: MyType[] = ["a", "b"]; ``` ## Configuration This rule accepts a configuration object with the following properties: ## default type: `"array" | "array-simple" | "generic"` default: `"array"` The array type expected for mutable cases. ## readonly type: `"array" | "array-simple" | "generic"` default: `null` The array type expected for readonly cases. If omitted, the value for `default` will be used. ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "typescript/array-type": "error" } } ``` ```bash [CLI] oxlint --deny typescript/array-type ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/arrow-body-style.md --- url: /docs/guide/usage/linter/rules/eslint/arrow-body-style.md --- ### What it does This rule can enforce or disallow the use of braces around arrow function body. Arrow functions can use either: * a block body `() => { ... }` * or a concise body `() => expression` with an implicit return. ### Why is this bad? Inconsistent use of block vs. concise bodies makes code harder to read. Concise bodies are limited to a single expression, whose value is implicitly returned. ### Options First option: * Type: `string` * Enum: `"always"`, `"as-needed"`, `"never"` * Default: `"as-needed"` Possible values: * `never` enforces no braces around the function body (constrains arrow functions to the role of returning an expression) * `always` enforces braces around the function body * `as-needed` enforces no braces where they can be omitted (default) Second option: * Type: `object` * Properties: * `requireReturnForObjectLiteral`: `boolean` (default: `false`) - requires braces and an explicit return for object literals. Note: This option only applies when the first option is `"as-needed"`. Example configuration: ```json { "arrow-body-style": ["error", "as-needed", { "requireReturnForObjectLiteral": true }] } ``` ### Examples #### `"never"` Examples of **incorrect** code for this rule with the `never` option: ```js /* arrow-body-style: ["error", "never"] */ /* ✘ Bad: */ const foo = () => { return 0; }; ``` Examples of **correct** code for this rule with the `never` option: ```js /* arrow-body-style: ["error", "never"] */ /* ✔ Good: */ const foo = () => 0; const bar = () => ({ foo: 0 }); ``` #### `"always"` Examples of **incorrect** code for this rule with the `always` option: ```js /* arrow-body-style: ["error", "always"] */ /* ✘ Bad: */ const foo = () => 0; ``` Examples of **correct** code for this rule with the `always` option: ```js /* arrow-body-style: ["error", "always"] */ /* ✔ Good: */ const foo = () => { return 0; }; ``` #### `"as-needed"` (default) Examples of **incorrect** code for this rule with the `as-needed` option: ```js /* arrow-body-style: ["error", "as-needed"] */ /* ✘ Bad: */ const foo = () => { return 0; }; ``` Examples of **correct** code for this rule with the `as-needed` option: ```js /* arrow-body-style: ["error", "as-needed"] */ /* ✔ Good: */ const foo1 = () => 0; const foo2 = (retv, name) => { retv[name] = true; return retv; }; const foo3 = () => { bar(); }; ``` #### `"as-needed"` with `requireReturnForObjectLiteral` Examples of **incorrect** code for this rule with the `{ "requireReturnForObjectLiteral": true }` option: ```js /* arrow-body-style: ["error", "as-needed", { "requireReturnForObjectLiteral": true }] */ /* ✘ Bad: */ const foo = () => ({}); const bar = () => ({ bar: 0 }); ``` Examples of **correct** code for this rule with the `{ "requireReturnForObjectLiteral": true }` option: ```js /* arrow-body-style: ["error", "as-needed", { "requireReturnForObjectLiteral": true }] */ /* ✔ Good: */ const foo = () => {}; const bar = () => { return { bar: 0 }; }; ``` ## Configuration ### The 1st option type: `"as-needed" | "always" | "never"` ### The 2nd option This option is an object with the following properties: #### requireReturnForObjectLiteral type: `boolean` default: `false` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "arrow-body-style": "error" } } ``` ```bash [CLI] oxlint --deny arrow-body-style ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/learn/architecture/ast-tools.md --- url: /docs/learn/architecture/ast-tools.md --- # AST Tools The [AST Tools](https://github.com/oxc-project/oxc/tree/main/tasks/ast_tools) task serves as our secret weapon for managing all generated files. These tools include the AST builder, visitors, traits like `ContentEq` and `ContentHash`, and TypeScript types - all of which are machine-generated. For instance, the following files are automatically generated: * `crates/oxc_ast/src/generated/ast_builder.rs` * `crates/oxc_ast/src/generated/visit.rs` * `crates/oxc_ast/src/generated/visit_mut.rs` * `crates/oxc_ast/src/generated/derive_content_eq.rs` * `crates/oxc_ast/src/generated/derive_content_hash.rs` * `npm/oxc-types/src/generated/types.d.ts` ## Background Rust's compile time is notoriously slow, and using procedural macros to generate this much code worsens the issue. Requiring users to wait for code generation to complete at build time would significantly hinder the development experience for downstream projects. Both cold and incremental build times [can regress drastically](https://github.com/swc-project/swc/issues/7071). ## The RFC The team discussed the topic in [RFC: codegen AST related codes](https://github.com/oxc-project/oxc/issues/4134) and agreed on the following requirements and user story: ### Requirements * No build.rs published to the user. * All generated code are checked into git. * No nightly. * Rust code is source of truth, need to parse types marked `#[ast]`. * Avoid compile-time procedural macros as much as possible. ### Workflow * A user changes code in repo. * A watch change picks it up. * Parse all types marked `#[ast]`. * Record details of all AST types in a schema. * Generate code from schema and save to files. ## Infrastructure More details to follow. --- # Source: https://oxc.rs/docs/contribute/parser/ast.md # Source: https://oxc.rs/docs/learn/parser_in_rust/ast.md --- url: /docs/learn/parser_in_rust/ast.md --- # AST The parser in the upcoming chapter is responsible for turning Tokens into an abstract syntax tree (AST). It is much nicer to work on the AST compared to the source text. All JavaScript toolings work on the AST level, for example: * A linter (e.g. ESLint) checks the AST for errors * A formatter (e.g.prettier) prints the AST back to JavaScript text * A minifier (e.g. terser) transforms the AST * A bundler connects all import and export statements between ASTs from different files In this chapter, let's construct a JavaScript AST by using Rust structs and enums. ## Getting familiar with the AST To get ourselves comfortable with an AST, let's visit [ASTExplorer](https://astexplorer.net/) and see what it looks like. On the top panel, select JavaScript, and then `acorn`, type in `var a` and we will see a tree view and a JSON view. ```json { "type": "Program", "start": 0, "end": 5, "body": [ { "type": "VariableDeclaration", "start": 0, "end": 5, "declarations": [ { "type": "VariableDeclarator", "start": 4, "end": 5, "id": { "type": "Identifier", "start": 4, "end": 5, "name": "a" }, "init": null } ], "kind": "var" } ], "sourceType": "script" } ``` Since this is a tree, every object is a node with a type name (e.g. `Program`, `VariableDeclaration`, `VariableDeclarator`, `Identifier`). `start` and `end` are the offsets from the source. ## estree [estree](https://github.com/estree/estree) is a community standard grammar specification for JavaScript, it defines [all the AST nodes](https://github.com/estree/estree/blob/master/es5.md) so different tools can be compatible with each other. The basic building block for any AST node is the `Node` type: ```rust #[derive(Debug, Default, Clone, Copy, Serialize, PartialEq, Eq)] pub struct Node { /// Start offset in source pub start: usize, /// End offset in source pub end: usize, } impl Node { pub fn new(start: usize, end: usize) -> Self { Self { start, end } } } ``` AST for `var a` is defined as ```rust pub struct Program { pub node: Node, pub body: Vec, } pub enum Statement { VariableDeclarationStatement(VariableDeclaration), } pub struct VariableDeclaration { pub node: Node, pub declarations: Vec, } pub struct VariableDeclarator { pub node: Node, pub id: BindingIdentifier, pub init: Option, } pub struct BindingIdentifier { pub node: Node, pub name: String, } pub enum Expression { } ``` Rust does not have inheritance, so `Node` is added to each struct (this is called "composition over Inheritance"). `Statement`s and `Expression`s are enums because they will be expanded with a lot of other node types, for example: ```rust pub enum Expression { AwaitExpression(AwaitExpression), YieldExpression(YieldExpression), } pub struct AwaitExpression { pub node: Node, pub expression: Box, } pub struct YieldExpression { pub node: Node, pub expression: Box, } ``` The `Box` is needed because self-referential structs are not allowed in Rust. :::info JavaScript grammar has a lot of nuisances, read the [grammar tutorial](/docs/learn/ecmascript/grammar.html) for amusement. ::: ## Rust Optimizations ### Memory Allocations We need to look out for heap-allocated structs such as `Vec` and `Box` because heap allocations are not cheap. Take a look at the [real world implementation from swc](https://github.com/swc-project/swc/blob/main/crates/swc_ecma_ast/src/expr.rs), we can see that an AST can have lots of `Box`s and `Vec`s, and also note that the `Statement` and `Expression` enums contain a dozen of enum variants. ### Memory Arena Using the global memory allocator for the AST is actually not really efficient. Every `Box` and `Vec` are allocated on demand and then dropped separately. What we would like to do is pre-allocate memory and drop it in wholesale. :::info See also [Arenas in Rust](https://manishearth.github.io/blog/2021/03/15/arenas-in-rust) and [Flattening ASTs](https://www.cs.cornell.edu/~asampson/blog/flattening.html) for more background on storing ASTs in memory arenas. ::: [`bumpalo`](https://docs.rs/bumpalo/latest/bumpalo/) is a very good candidate for our use case, according to its documentation: > Bump allocation is a fast, but limited approach to allocation. > We have a chunk of memory, and we maintain a pointer within that memory. Whenever we allocate an object, > we do a quick check that we have enough capacity left in our chunk to allocate the object and then update the pointer by the object’s size. That’s it! > > The disadvantage of bump allocation is that there is no general way to deallocate individual objects or reclaim the memory region for a no-longer-in-use object. > > These trade offs make bump allocation well-suited for phase-oriented allocations. That is, a group of objects that will all be allocated during the same program phase, used, and then can all be deallocated together as a group. By using `bumpalo::collections::Vec` and `bumpalo::boxed::Box`, our AST will have lifetimes added to it: ```rust use bumpalo::collections::Vec; use bumpalo::boxed::Box; pub enum Expression<'a> { AwaitExpression(Box<'a, AwaitExpression>), YieldExpression(Box<'a, YieldExpression>), } pub struct AwaitExpression<'a> { pub node: Node, pub expression: Expression<'a>, } pub struct YieldExpression<'a> { pub node: Node, pub expression: Expression<'a>, } ``` :::info Please be cautious if we are not comfortable dealing with lifetimes at this stage. Our program will work fine without a memory arena. Code in the following chapters does not demonstrate the use of a memory arena for simplicity. ::: ### Enum Size The first optimization we are going to make is to reduce the size of the enums. It is known that the byte size of a Rust enum is the union of all its variants. For example, the following enum will take up 56 bytes (1 byte for the tag, 48 bytes for the payload, and 8 bytes for alignment). ```rust enum Name { Anonymous, // 0 byte payload Nickname(String), // 24 byte payload FullName{ first: String, last: String }, // 48 byte payload } ``` :::info This example is taken from [this blog post](https://adeschamps.github.io/enum-size) ::: As for the `Expression` and `Statement` enums, they can take up to more than 200 bytes with our current setup. These 200 bytes need to be passed around, or accessed every time we do a `matches!(expr, Expression::AwaitExpression(_))` check, which is not very cache friendly for performance. A better approach would be to box the enum variants and only carry 16 bytes around. ```rust pub enum Expression { AwaitExpression(Box), YieldExpression(Box), } pub struct AwaitExpression { pub node: Node, pub expression: Expression, } pub struct YieldExpression { pub node: Node, pub expression: Expression, } ``` To make sure the enums are indeed 16 bytes on 64-bit systems, we can use `std::mem::size_of`. ```rust #[test] fn no_bloat_enum_sizes() { use std::mem::size_of; assert_eq!(size_of::(), 16); assert_eq!(size_of::(), 16); } ``` "no bloat enum sizes" test cases can often be seen in the Rust compiler source code for ensuring small enum sizes. ```rust // https://github.com/rust-lang/rust/blob/9c20b2a8cc7588decb6de25ac6a7912dcef24d65/compiler/rustc_ast/src/ast.rs#L3033-L3042 // Some nodes are used a lot. Make sure they don't unintentionally get bigger. #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] mod size_asserts { use super::*; use rustc_data_structures::static_assert_size; // These are in alphabetical order, which is easy to maintain. static_assert_size!(AssocItem, 160); static_assert_size!(AssocItemKind, 72); static_assert_size!(Attribute, 32); static_assert_size!(Block, 48); ``` To find other large types, we can run ```bash RUSTFLAGS=-Zprint-type-sizes cargo +nightly build -p name_of_the_crate --release ``` and see ``` print-type-size type: `ast::js::Statement`: 16 bytes, alignment: 8 bytes print-type-size discriminant: 8 bytes print-type-size variant `BlockStatement`: 8 bytes print-type-size field `.0`: 8 bytes print-type-size variant `BreakStatement`: 8 bytes print-type-size field `.0`: 8 bytes print-type-size variant `ContinueStatement`: 8 bytes print-type-size field `.0`: 8 bytes print-type-size variant `DebuggerStatement`: 8 bytes print-type-size field `.0`: 8 bytes ``` ## JSON Serialization [serde](https://serde.rs/) can be used serialize the AST to JSON. Some techniques are needed to make it `estree` compatible. Here are some examples: ```rust use serde::Serialize; #[derive(Debug, Clone, Serialize, PartialEq)] #[serde(tag = "type")] #[cfg_attr(feature = "estree", serde(rename = "Identifier"))] pub struct IdentifierReference { #[serde(flatten)] pub node: Node, pub name: Atom, } #[derive(Debug, Clone, Serialize, PartialEq, Hash)] #[serde(tag = "type")] #[cfg_attr(feature = "estree", serde(rename = "Identifier"))] pub struct BindingIdentifier { #[serde(flatten)] pub node: Node, pub name: Atom, } #[derive(Debug, Serialize, PartialEq)] #[serde(untagged)] pub enum Expression<'a> { ... } ``` * `serde(tag = "type")` is used to make the struct name a "type" field, i.e. `{ "type" : "..." }` * `cfg_attr` + `serde(rename)` is used to rename different struct names to the same name, since `estree` does not distinguish different identifiers * `serde(untagged)` on the enum is used to not create an extra JSON object for the enum --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/jsx_a11y/autocomplete-valid.md --- url: /docs/guide/usage/linter/rules/jsx_a11y/autocomplete-valid.md --- ### What it does Enforces that an element's autocomplete attribute must be a valid value. ### Why is this bad? Incorrectly using the autocomplete attribute may decrease the accessibility of the website for users. ### Examples Examples of **incorrect** code for this rule: ```jsx ``` Examples of **correct** code for this rule: ```jsx ``` ## Configuration This rule accepts a configuration object with the following properties: ### inputComponents type: `string[]` default: `["input"]` List of custom component names that should be treated as input elements. ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["jsx-a11y"], "rules": { "jsx-a11y/autocomplete-valid": "error" } } ``` ```bash [CLI] oxlint --deny jsx-a11y/autocomplete-valid --jsx-a11y-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/automatic-fixes.md --- url: /docs/guide/usage/linter/automatic-fixes.md description: 'Apply safe, suggested, and dangerous fixes with Oxlint.' --- # Automatic fixes Oxlint can automatically fix some lint violations. Automatic fixes are only applied when passing the relevant CLI flags. You choose when to apply them. In the code editor integrations (such as VS Code), automatic fixes are exposed as "code actions" that you can apply in-editor. ## Safe fixes Safe fixes are changes that do not alter program behavior. Apply safe fixes: ```bash oxlint --fix ``` ## Suggestions Suggestions are changes that may alter behavior or may not match your intent. Apply suggestions: ```bash oxlint --fix-suggestions ``` ## Dangerous fixes Dangerous fixes are aggressive changes that may break your code. Apply dangerous fixes: ```bash oxlint --fix-dangerously ``` ## Combining fix modes You can combine safe fixes and suggestions: ```bash oxlint --fix --fix-suggestions ``` You can also include dangerous fixes: ```bash oxlint --fix --fix-suggestions --fix-dangerously ``` ## Rule support Not all rules provide fixes. Some rules support safe fixes, some provide suggestions, and some do not provide fixes yet. If a rule is missing a fixer, contributions are welcome. ## Type-aware linting and fixes [Type-aware linting](/docs/guide/usage/linter/type-aware) requires building the project. You can apply safe fixes with type-aware linting enabled: ```bash oxlint --type-aware --fix ``` --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/promise/avoid-new.md --- url: /docs/guide/usage/linter/rules/promise/avoid-new.md --- ### What it does Disallow creating promises with `new Promise()`. ### Why is this bad? Many cases that use `new Promise()` could be refactored to use an `async` function. `async` is considered more idiomatic in modern JavaScript. ### Examples Examples of **incorrect** code for this rule: ```javascript function foo() { return new Promise((resolve, reject) => { /* ... */ }); } ``` Examples of **correct** code for this rule: ```javascript async function foo() { // ... } const bar = await Promise.all([baz(), bang()]); ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["promise"], "rules": { "promise/avoid-new": "error" } } ``` ```bash [CLI] oxlint --deny promise/avoid-new --promise-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/typescript/await-thenable.md ## What it does This rule disallows awaiting a value that is not a Thenable. ## Why is this bad? While it is valid JavaScript to await a non-Promise-like value (it will resolve immediately), this practice can be confusing for readers who are not aware of this behavior. It can also be a sign of a programmer error, such as forgetting to add parentheses to call a function that returns a Promise. ## Examples Examples of **incorrect** code for this rule: ```typescript await 12; await (() => {}); // non-Promise values await Math.random; await { then() {} }; // this is not a Promise - it's a function that returns a Promise declare const getPromise: () => Promise; await getPromise; ``` Examples of **correct** code for this rule: ```typescript await Promise.resolve('value'); await Promise.reject(new Error()); // Promise-like values await { then(onfulfilled, onrejected) { onfulfilled('value'); }, }; // this is a Promise - produced by calling a function declare const getPromise: () => Promise; await getPromise(); ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "typescript/await-thenable": "error" } } ``` ```bash [CLI] oxlint --type-aware --deny typescript/await-thenable ``` ::: ## References * Rule Source * Rule Source (tsgolint) --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/oxc/bad-array-method-on-arguments.md --- url: /docs/guide/usage/linter/rules/oxc/bad-array-method-on-arguments.md --- ### What it does This rule applies when an array method is called on the arguments object itself. ### Why is this bad? The [arguments object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments) is not an array, but an array-like object. It should be converted to a real array before calling an array method. Otherwise, a TypeError exception will be thrown because of the non-existent method. Note that you probably don't need this rule if you are using exclusively TypeScript, as it will catch these errors when typechecking. `arguments` usage is usually discouraged in modern JavaScript, and you should prefer using rest parameters instead, e.g. `function sum(...args)`. ### Examples Examples of **incorrect** code for this rule: ```javascript function add(x, y) { return x + y; } function sum() { return arguments.reduce(add, 0); } ``` Examples of **correct** code for this rule: ```javascript function add(x, y) { return x + y; } function sum(...args) { return args.reduce(add, 0); } ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "oxc/bad-array-method-on-arguments": "error" } } ``` ```bash [CLI] oxlint --deny oxc/bad-array-method-on-arguments ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/oxc/bad-bitwise-operator.md --- url: /docs/guide/usage/linter/rules/oxc/bad-bitwise-operator.md --- ### What it does This rule applies when bitwise operators are used where logical operators are expected. ### Why is this bad? Bitwise operators have different results from logical operators and a `TypeError` exception may be thrown because short-circuit evaluation is not applied. (In short-circuit evaluation, right operand evaluation is skipped according to left operand value, e.g. `x` is `false` in `x && y`.) It is obvious that logical operators are expected in the following code patterns: ```javascript e && e.x; e || {}; e || ""; ``` ### Examples Examples of **incorrect** code for this rule: ```javascript if (obj & obj.prop) { console.log(obj.prop); } options = options | {}; input |= ""; ``` Examples of **correct** code for this rule: ```javascript if (obj && obj.prop) { console.log(obj.prop); } options = options || {}; input ||= ""; ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "oxc/bad-bitwise-operator": "error" } } ``` ```bash [CLI] oxlint --deny oxc/bad-bitwise-operator ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/oxc/bad-char-at-comparison.md --- url: /docs/guide/usage/linter/rules/oxc/bad-char-at-comparison.md --- ### What it does This rule warns when the return value of the `charAt` method is used to compare a string of length greater than 1. ### Why is this bad? The `charAt` method returns a string of length 1. If the return value is compared with a string of length greater than 1, the comparison will always be false. ### Examples Examples of **incorrect** code for this rule: ```javascript a.charAt(4) === "a2"; a.charAt(4) === "/n"; ``` Examples of **correct** code for this rule: ```javascript a.charAt(4) === "a"; a.charAt(4) === "\n"; ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "oxc/bad-char-at-comparison": "error" } } ``` ```bash [CLI] oxlint --deny oxc/bad-char-at-comparison ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/oxc/bad-comparison-sequence.md --- url: /docs/guide/usage/linter/rules/oxc/bad-comparison-sequence.md --- ### What it does This rule applies when the comparison operator is applied two or more times in a row. ### Why is this bad? Because comparison operator is a binary operator, it is impossible to compare three or more operands at once. If comparison operator is used to compare three or more operands, only the first two operands are compared and the rest is compared with its result of boolean type. ### Examples Examples of **incorrect** code for this rule: ```javascript if ((a == b) == c) { console.log("a, b, and c are the same"); } ``` Examples of **correct** code for this rule: ```javascript if (a == b && b == c) { console.log("a, b, and c are the same"); } ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "oxc/bad-comparison-sequence": "error" } } ``` ```bash [CLI] oxlint --deny oxc/bad-comparison-sequence ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/oxc/bad-min-max-func.md --- url: /docs/guide/usage/linter/rules/oxc/bad-min-max-func.md --- ### What it does Checks whether the clamp function `Math.min(Math.max(x, y), z)` always evaluate to a constant result because the arguments are in the wrong order. ### Why is this bad? The `Math.min(Math.max(x, y), z)` function is used to clamp a value between two other values. If the arguments are in the wrong order, the function will always evaluate to a constant result. ### Examples Examples of **incorrect** code for this rule: ```javascript Math.min(Math.max(100, x), 0); Math.max(1000, Math.min(0, z)); ``` Examples of **correct** code for this rule: ```javascript Math.max(0, Math.min(100, x)); Math.min(1000, Math.max(0, z)); ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "oxc/bad-min-max-func": "error" } } ``` ```bash [CLI] oxlint --deny oxc/bad-min-max-func ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/oxc/bad-object-literal-comparison.md --- url: /docs/guide/usage/linter/rules/oxc/bad-object-literal-comparison.md --- ### What it does Checks for comparisons between object and array literals. ### Why is this bad? Comparing a variable to an object or array literal will always return false as object and array literals are never equal to each other. If you want to check if an object or array is empty, use `Object.entries()` or `Object.keys()` and their lengths. ### Examples Examples of **incorrect** code for this rule: ```javascript if (x === {}) { } if (arr !== []) { } ``` Examples of **correct** code for this rule: ```javascript if (typeof x === "object" && Object.keys(x).length === 0) { } if (Array.isArray(x) && x.length === 0) { } ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "oxc/bad-object-literal-comparison": "error" } } ``` ```bash [CLI] oxlint --deny oxc/bad-object-literal-comparison ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/oxc/bad-replace-all-arg.md --- url: /docs/guide/usage/linter/rules/oxc/bad-replace-all-arg.md --- ### What it does This rule warns when the `replaceAll` method is called with a regular expression that does not have the global flag (g). ### Why is this bad? The `replaceAll` method replaces all occurrences of a string with another string. If the global flag (g) is not used in the regular expression, only the first occurrence of the string will be replaced. ### Examples Examples of **incorrect** code for this rule: ```javascript withSpaces.replaceAll(/\s+/, ","); ``` Examples of **correct** code for this rule: ```javascript withSpaces.replaceAll(/\s+/g, ","); ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "oxc/bad-replace-all-arg": "error" } } ``` ```bash [CLI] oxlint --deny oxc/bad-replace-all-arg ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/typescript/ban-ts-comment.md ## What it does This rule lets you set which directive comments you want to allow in your codebase. ## Why is this bad? Using TypeScript directives to suppress TypeScript compiler errors reduces the effectiveness of TypeScript overall. ## Examples Examples of **incorrect** code for this rule: ```ts if (false) { // @ts-ignore: Unreachable code error console.log("hello"); } ``` ## Configuration This rule allows you to specify how different TypeScript directive comments should be handled. For each directive (`@ts-expect-error`, `@ts-ignore`, `@ts-nocheck`, `@ts-check`), you can choose one of the following options: * `true`: Disallow the directive entirely, preventing its use in the entire codebase. * `false`: Allow the directive without any restrictions. * `"allow-with-description"`: Allow the directive only if it is followed by a description explaining its use. The description must meet the minimum length specified by `minimumDescriptionLength`. * `{ "descriptionFormat": "" }`: Allow the directive only if the description matches the specified regex pattern. For example: ```json { "ts-expect-error": "allow-with-description", "ts-ignore": true, "ts-nocheck": { "descriptionFormat": "^: TS\\d+ because .+$" }, "ts-check": false, "minimumDescriptionLength": 3 } ``` This rule accepts a configuration object with the following properties: ## minimumDescriptionLength type: `integer` default: `3` Minimum description length required when using directives with `allow-with-description`. ## ts-check How to handle the `@ts-check` directive. ## ts-expect-error How to handle the `@ts-expect-error` directive. ## ts-ignore How to handle the `@ts-ignore` directive. ## ts-nocheck How to handle the `@ts-nocheck` directive. ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "typescript/ban-ts-comment": "error" } } ``` ```bash [CLI] oxlint --deny typescript/ban-ts-comment ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/typescript/ban-tslint-comment.md ## What it does This rule disallows `tslint:` comments ## Why is this bad? Useful when migrating from TSLint to ESLint. Once TSLint has been removed, this rule helps locate TSLint annotations ## Examples Examples of **incorrect** code for this rule: ```ts // tslint:disable-next-line someCode(); ``` Examples of **correct** code for this rule: ```ts someCode(); ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "typescript/ban-tslint-comment": "error" } } ``` ```bash [CLI] oxlint --deny typescript/ban-tslint-comment ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/typescript/ban-types.md ## What it does This rule bans specific types and can suggest alternatives. Note that it does not ban the corresponding runtime objects from being used. ## Why is this bad? Some built-in types have aliases, while some types are considered dangerous or harmful. It's often a good idea to ban certain types to help with consistency and safety. ## Examples Examples of **incorrect** code for this rule: ```typescript let foo: String = "foo"; let bar: Boolean = true; ``` Examples of **correct** code for this rule: ```typescript let foo: string = "foo"; let bar: boolean = true; ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "typescript/ban-types": "error" } } ``` ```bash [CLI] oxlint --deny typescript/ban-types ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/benchmarks.md --- url: /docs/guide/benchmarks.md --- # All Benchmarks ## Parser Oxc's parser is at least 3x faster than swc and 5x faster than Biome. Please note that it is not an apple-to-apple comparison with Biome. Biome's parser [produces a CST](https://biomejs.dev/internals/architecture) instead of an AST, which requires a lot more work. See repository [bench-javascript-parser-written-in-rust](https://github.com/oxc-project/bench-javascript-parser-written-in-rust). ## Transformer * Compared to swc, oxc transformer is 4x faster, uses 20% less memory, and is 35 MB smaller in package size (from swc's 37MB). * Compared to babel, oxc transformer is 40x faster, uses 70% less memory, and is 19 MB smaller with 168 npm packages less to install. See repository [bench-transformer](https://github.com/oxc-project/bench-transformer). ## Linter Oxlint is 50x - 100x faster than ESLint depending on the number of CPU cores. See repository [bench-javascript-linter](https://github.com/oxc-project/bench-javascript-linter). ## Formatter Oxfmt is 3x faster than Biome, 35x faster than prettier. See repository [bench-formatter](https://github.com/oxc-project/bench-formatter). ## Resolver `oxc-resolver` is 30x faster than webpack's `enhanced-resolve`. See repository [bench-resolver](https://github.com/oxc-project/bench-resolver). --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/block-scoped-var.md --- url: /docs/guide/usage/linter/rules/eslint/block-scoped-var.md --- ### What it does Enforces that variables are both **declared** and **used** within the same block scope. This rule prevents accidental use of variables outside their intended block, mimicking C-style block scoping in JavaScript. ### Why is this bad? JavaScript’s `var` declarations are hoisted to the top of their enclosing function, which can cause variables declared in a block (e.g., inside an `if` or `for`) to be accessible outside of it. This can lead to hard-to-find bugs. By enforcing block scoping, this rule helps avoid hoisting issues and aligns more closely with how other languages treat block variables. ### Examples Examples of **incorrect** code for this rule: ```js /* block-scoped-var: "error" */ function doIf() { if (true) { var build = true; } console.log(build); } function doLoop() { for (var i = 0; i < 10; i++) { // do something } console.log(i); // i is accessible here } function doSomething() { if (true) { var foo = 1; } if (false) { foo = 2; } } function doTry() { try { var foo = 1; } catch (e) { console.log(foo); } } ``` Examples of **correct** code for this rule: ```js /* block-scoped-var: "error" */ function doIf() { var build; if (true) { build = true; } console.log(build); } function doLoop() { var i; for (i = 0; i < 10; i++) { // do something } console.log(i); } function doSomething() { var foo; if (true) { foo = 1; } if (false) { foo = 2; } } function doTry() { var foo; try { foo = 1; } catch (e) { console.log(foo); } } ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "block-scoped-var": "error" } } ``` ```bash [CLI] oxlint --deny block-scoped-var ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/oxc/branches-sharing-code.md --- url: /docs/guide/usage/linter/rules/oxc/branches-sharing-code.md --- ### What it does Checks if the `if` and `else` blocks contain shared code that can be moved out of the blocks. ### Why is this bad? Duplicate code is less maintainable. Extracting common code from branches makes the code more DRY (Don't Repeat Yourself) and easier to maintain. ### Examples Examples of **incorrect** code for this rule: ```javascript if (condition) { console.log("Hello"); return 13; } else { console.log("Hello"); return 42; } if (condition) { doSomething(); cleanup(); } else { doSomethingElse(); cleanup(); } ``` Examples of **correct** code for this rule: ```javascript console.log("Hello"); if (condition) { return 13; } else { return 42; } if (condition) { doSomething(); } else { doSomethingElse(); } cleanup(); ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "oxc/branches-sharing-code": "error" } } ``` ```bash [CLI] oxlint --deny oxc/branches-sharing-code ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/branding.md --- url: /branding.md --- # Branding * Designed by: [@tongtong-lu](https://github.com/tongtong-lu) and [@guan-wy](https://github.com/guan-wy) * [GitHub Repository](https://github.com/oxc-project/oxc-assets) * Font: https://fonts.google.com/specimen/IBM+Plex+Mono ## Capitalization `Oxc` ## Icons ### SVG ### PNG ### ICO ## With bubbles For larger displays and stickers. ### PNG ### SVG ## Banners ### Universal Background ### White and Dark Background ## Visuals Colors: #91EDE9 #FF915C #48ACBA #2B3C5A #8A380F ## uwu uwu images designed by [icarusgkx](https://x.com/icarusgkx) --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/react/button-has-type.md ## What it does Enforces explicit `type` attribute for all the `button` HTML elements. ## Why is this bad? The default value of `type` attribute for `button` HTML element is `"submit"` which is often not the desired behavior and may lead to unexpected page reloads. ## Examples Examples of **incorrect** code for this rule: ```jsx
; React.createElement("div", {}, React.createElement("button", {}, React.createElement("input"))); ``` Examples of **correct** code for this rule: ```jsx // ["error", { "forbid": ["button"] }] } ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["nextjs"], "rules": { "nextjs/no-async-client-component": "error" } } ``` ```bash [CLI] oxlint --deny nextjs/no-async-client-component --nextjs-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/oxc/no-async-endpoint-handlers.md --- url: /docs/guide/usage/linter/rules/oxc/no-async-endpoint-handlers.md --- ### What it does Disallows the use of `async` functions as Express endpoint handlers. ### Why is this bad? Before v5, Express will not automatically handle Promise rejections from handler functions with your application's error handler. You must instead explicitly pass the rejected promise to `next()`. ```js const app = express(); app.get("/", (req, res, next) => { new Promise((resolve, reject) => { return User.findById(req.params.id); }) .then((user) => res.json(user)) .catch(next); }); ``` If this is not done, your server will crash with an unhandled promise rejection. ```js const app = express(); app.get("/", async (req, res) => { // Server will crash if User.findById rejects const user = await User.findById(req.params.id); res.json(user); }); ``` See [Express' Error Handling Guide](https://expressjs.com/en/guide/error-handling.html) for more information. ### Examples Examples of **incorrect** code for this rule: ```js const app = express(); app.get("/", async (req, res) => { const user = await User.findById(req.params.id); res.json(user); }); const router = express.Router(); router.use(async (req, res, next) => { const user = await User.findById(req.params.id); req.user = user; next(); }); const createUser = async (req, res) => { const user = await User.create(req.body); res.json(user); }; app.post("/user", createUser); // Async handlers that are imported will not be detected because each // file is checked in isolation. This does not trigger the rule, but still // violates it and _will_ result in server crashes. const asyncHandler = require("./asyncHandler"); app.get("/async", asyncHandler); ``` Examples of **correct** code for this rule: ```js const app = express(); // not async app.use((req, res, next) => { req.receivedAt = Date.now(); }); app.get("/", (req, res, next) => { fs.readFile("/file-does-not-exist", (err, data) => { if (err) { next(err); // Pass errors to Express. } else { res.send(data); } }); }); const asyncHandler = async (req, res) => { const user = await User.findById(req.params.id); res.json(user); }; app.get("/user", (req, res, next) => asyncHandler(req, res).catch(next)); ``` ## Configuration This rule accepts a configuration object with the following properties: ### allowedNames type: `string[]` default: `[]` An array of names that are allowed to be async. ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "oxc/no-async-endpoint-handlers": "error" } } ``` ```bash [CLI] oxlint --deny oxc/no-async-endpoint-handlers ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/no-async-promise-executor.md --- url: /docs/guide/usage/linter/rules/eslint/no-async-promise-executor.md --- ### What it does Disallow using an async function as a Promise executor. ### Why is this bad? The `new Promise` constructor accepts an executor function as an argument, which has `resolve` and `reject` parameters that can be used to control the state of the created Promise. For example: ```javascript const result = new Promise(function executor(resolve, reject) { readFile("foo.txt", function (err, result) { if (err) { reject(err); } else { resolve(result); } }); }); ``` The executor function can also be an `async function`. However, this is usually a mistake, for a few reasons: * If an async executor function throws an error, the error will be lost and won’t cause the newly-constructed `Promise` to reject.This could make it difficult to debug and handle some errors. * If a `Promise` executor function is using `await`, this is usually a sign that it is not actually necessary to use the new `Promise` constructor, or the scope of the new `Promise` constructor can be reduced. ### Examples Examples of **incorrect** code for this rule: ```javascript const foo = new Promise(async (resolve, reject) => { readFile("foo.txt", function (err, result) { if (err) { reject(err); } else { resolve(result); } }); }); const result = new Promise(async (resolve, reject) => { resolve(await foo); }); ``` Examples of **correct** code for this rule: ```javascript const foo = new Promise((resolve, reject) => { readFile("foo.txt", function (err, result) { if (err) { reject(err); } else { resolve(result); } }); }); const result = Promise.resolve(foo); ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "no-async-promise-executor": "error" } } ``` ```bash [CLI] oxlint --deny no-async-promise-executor ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/jsx_a11y/no-autofocus.md --- url: /docs/guide/usage/linter/rules/jsx_a11y/no-autofocus.md --- ### What it does Enforce that `autoFocus` prop is not used on elements. ### Why is this bad? Autofocusing elements can cause usability issues for sighted and non-sighted users alike. It can be disorienting when focus is shifted without user input and can interfere with assistive technologies. Users should control when and where focus moves on a page. ### Examples Examples of **incorrect** code for this rule: ```jsx
``` Examples of **correct** code for this rule: ```jsx
``` ## Configuration This rule accepts a configuration object with the following properties: ### ignoreNonDOM type: `boolean` default: `false` Determines if developer-created components are checked. ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["jsx-a11y"], "rules": { "jsx-a11y/no-autofocus": "error" } } ``` ```bash [CLI] oxlint --deny jsx-a11y/no-autofocus --jsx-a11y-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/unicorn/no-await-expression-member.md ## What it does Disallows member access from `await` expressions. ## Why is this bad? When accessing a member from an `await` expression, the `await` expression has to be parenthesized, which is not readable. ## Examples Examples of **incorrect** code for this rule: ```javascript async function bad() { const secondElement = (await getArray())[1]; } ``` Examples of **correct** code for this rule: ```javascript async function good() { const [, secondElement] = await getArray(); } ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "unicorn/no-await-expression-member": "error" } } ``` ```bash [CLI] oxlint --deny unicorn/no-await-expression-member ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/no-await-in-loop.md --- url: /docs/guide/usage/linter/rules/eslint/no-await-in-loop.md --- ### What it does This rule disallows the use of `await` within loop bodies. (for, for-in, for-of, while, do-while). ### Why is this bad? It potentially indicates that the async operations are not being effectively parallelized. Instead, they are being run in series, which can lead to poorer performance. ### Examples Examples of **incorrect** code for this rule: ```javascript async function bad() { for (const user of users) { const userRecord = await getUserRecord(user); } } ``` Examples of **correct** code for this rule: ```javascript async function good() { await Promise.all(users.map((user) => getUserRecord(user))); } ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "no-await-in-loop": "error" } } ``` ```bash [CLI] oxlint --deny no-await-in-loop ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/unicorn/no-await-in-promise-methods.md ## What it does Disallow using `await` in `Promise` method parameters ## Why is this bad? Using `await` on promises passed as arguments to `Promise.all()`, `Promise.allSettled()`, `Promise.any()`, or `Promise.race()` is likely a mistake. ## Examples Examples of **incorrect** code for this rule: ```javascript async function foo() { Promise.all([await promise, anotherPromise]); Promise.allSettled([await promise, anotherPromise]); Promise.any([await promise, anotherPromise]); Promise.race([await promise, anotherPromise]); } ``` Examples of **correct** code for this rule: ```javascript async function foo() { Promise.all([promise, anotherPromise]); Promise.allSettled([promise, anotherPromise]); Promise.any([promise, anotherPromise]); Promise.race([promise, anotherPromise]); } ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "unicorn/no-await-in-promise-methods": "error" } } ``` ```bash [CLI] oxlint --deny unicorn/no-await-in-promise-methods ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/oxc/no-barrel-file.md --- url: /docs/guide/usage/linter/rules/oxc/no-barrel-file.md --- ### What it does Disallow the use of barrel files where the file contains `export *` statements, and the total number of modules exceed a threshold. The default threshold is 100. ### Why is this bad? Barrel files that re-export many modules can significantly slow down applications and bundlers. When a barrel file exports a large number of modules, importing from it forces the runtime or bundler to process all the exported modules, even if only a few are actually used. This leads to slower startup times and larger bundle sizes. References: * * ### Examples Invalid: ```javascript export * from "foo"; // where `foo` loads a subtree of 100 modules import * as ns from "foo"; // where `foo` loads a subtree of 100 modules ``` Valid: ```javascript export { foo } from "foo"; ``` ## Configuration This rule accepts a configuration object with the following properties: ### threshold type: `integer` default: `100` The maximum number of modules that can be re-exported via `export *` before the rule is triggered. ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "oxc/no-barrel-file": "error" } } ``` ```bash [CLI] oxlint --deny oxc/no-barrel-file ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/typescript/no-base-to-string.md ## What it does This rule requires toString() and toLocaleString() calls to only be called on objects which provide useful information when stringified. ## Why is this bad? JavaScript's toString() method returns '\[object Object]' on plain objects, which is not useful information. This rule prevents toString() and toLocaleString() from being called on objects that return less useful strings. ## Examples Examples of **incorrect** code for this rule: ```ts // These will evaluate to '[object Object]' ({}).toString(); ({ foo: "bar" }).toString(); ({ foo: "bar" }).toLocaleString(); // This will evaluate to 'Symbol()' Symbol("foo").toString(); ``` Examples of **correct** code for this rule: ```ts const someString = "Hello world"; someString.toString(); const someNumber = 42; someNumber.toString(); const someBoolean = true; someBoolean.toString(); class CustomToString { toString() { return "CustomToString"; } } new CustomToString().toString(); ``` ## Configuration This rule accepts a configuration object with the following properties: ## checkUnknown type: `boolean` default: `false` Whether to also check values of type `unknown`. When `true`, calling toString on `unknown` values will be flagged. Default is `false`. ## ignoredTypeNames type: `string[]` default: `["Error", "RegExp", "URL", "URLSearchParams"]` A list of type names to ignore when checking for unsafe toString usage. These types are considered safe to call toString on even if they don't provide a custom implementation. ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "typescript/no-base-to-string": "error" } } ``` ```bash [CLI] oxlint --type-aware --deny typescript/no-base-to-string ``` ::: ## References * Rule Source * Rule Source (tsgolint) --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/no-bitwise.md --- url: /docs/guide/usage/linter/rules/eslint/no-bitwise.md --- ### What it does Disallow bitwise operators ### Why is this bad? The use of bitwise operators in JavaScript is very rare and often `&` or `|` is simply a mistyped `&&` or `||`, which will lead to unexpected behavior. ### Examples Examples of **incorrect** code for this rule: ```javascript var x = y | z; ``` ```javascript var x = y ^ z; ``` ```javascript var x = y >> z; ``` Examples of **correct** code for this rule: ```javascript var x = y || z; ``` ```javascript var x = y && z; ``` ```javascript var x = y > z; ``` ## Configuration This rule accepts a configuration object with the following properties: ### allow type: `string[]` default: `[]` The `allow` option permits the given list of bitwise operators to be used as exceptions to this rule. For example `{ "allow": ["~"] }` would allow the use of the bitwise operator `~` without restriction. Such as in the following: ```javascript ~[1, 2, 3].indexOf(1) === -1; ``` ### int32Hint type: `boolean` default: `false` When set to `true` the `int32Hint` option allows the use of bitwise OR in |0 pattern for type casting. For example with `{ "int32Hint": true }` the following is permitted: ```javascript const b = a | 0; ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "no-bitwise": "error" } } ``` ```bash [CLI] oxlint --deny no-bitwise ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/promise/no-callback-in-promise.md --- url: /docs/guide/usage/linter/rules/promise/no-callback-in-promise.md --- ### What it does Disallows calling a callback function (`cb()`) inside a `Promise.prototype.then()` or `Promise.prototype.catch()`. ### Why is this bad? Directly invoking a callback inside a `then()` or `catch()` method can lead to unexpected behavior, such as the callback being called multiple times. Additionally, mixing the callback and promise paradigms in this way can make the code confusing and harder to maintain. ### Examples Examples of **incorrect** code for this rule: ```js function callback(err, data) { console.log("Callback got called with:", err, data); throw new Error("My error"); } Promise.resolve() .then(() => callback(null, "data")) .catch((err) => callback(err.message, null)); ``` Examples of **correct** code for this rule: ```js Promise.resolve() .then((data) => { console.log(data); }) .catch((err) => { console.error(err); }); ``` ## Configuration This rule accepts a configuration object with the following properties: ### callbacks type: `string[]` default: `["callback", "cb", "done", "next"]` List of callback function names to check for within Promise `then` and `catch` methods. ### exceptions type: `string[]` default: `[]` List of callback function names to allow within Promise `then` and `catch` methods. ### timeoutsErr type: `boolean` default: `false` Boolean as to whether callbacks in timeout functions like `setTimeout` will err. ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["promise"], "rules": { "promise/no-callback-in-promise": "error" } } ``` ```bash [CLI] oxlint --deny promise/no-callback-in-promise --promise-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/no-caller.md --- url: /docs/guide/usage/linter/rules/eslint/no-caller.md --- ### What it does Disallow the use of `arguments.caller` or `arguments.callee`. ### Why is this bad? The use of `arguments.caller` and `arguments.callee` make several code optimizations impossible. They have been deprecated in JavaScript, and their use is forbidden while in strict mode. ```js function foo() { var callee = arguments.callee; } ``` This rule is aimed at discouraging the use of deprecated and sub-optimal code by disallowing the use of `arguments.caller` and `arguments.callee`. As such, it will warn when `arguments.caller` and `arguments.callee` are used. See [the MDN docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments/callee) for more information. ### Examples Examples of **incorrect** code for this rule: ```js function foo(n) { if (n <= 0) { return; } arguments.callee(n - 1); } [1, 2, 3, 4, 5].map(function (n) { return !(n > 1) ? 1 : arguments.callee(n - 1) * n; }); ``` Examples of **correct** code for this rule: ```js function foo(n) { if (n <= 0) { return; } foo(n - 1); } [1, 2, 3, 4, 5].map(function factorial(n) { return !(n > 1) ? 1 : factorial(n - 1) * n; }); ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "no-caller": "error" } } ``` ```bash [CLI] oxlint --deny no-caller ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/no-case-declarations.md --- url: /docs/guide/usage/linter/rules/eslint/no-case-declarations.md --- ### What it does Disallow lexical declarations in case clauses. ### Why is this bad? The reason is that the lexical declaration is visible in the entire switch block but it only gets initialized when it is assigned, which will only happen if the case where it is defined is reached. ### Examples Examples of **incorrect** code for this rule: ```javascript switch (foo) { case 1: let x = 1; break; case 2: const y = 2; break; case 3: function f() {} break; default: class C {} } ``` Examples of **correct** code for this rule: ```javascript switch (foo) { case 1: { let x = 1; break; } case 2: { const y = 2; break; } case 3: { function f() {} break; } default: { class C {} } } ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "no-case-declarations": "error" } } ``` ```bash [CLI] oxlint --deny no-case-declarations ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/react/no-children-prop.md ## What it does Checks that children are not passed using a prop. ## Why is this bad? Children should always be actual children, not passed in as a prop. When using JSX, the children should be nested between the opening and closing tags. When not using JSX, the children should be passed as additional arguments to `React.createElement`. ## Examples Examples of **incorrect** code for this rule: ```jsx
} /> React.createElement("div", { children: 'Children' }) ``` Examples of **correct** code for this rule: ```jsx
Children
Children Child 1 Child 2 React.createElement("div", {}, 'Children') React.createElement("div", 'Child 1', 'Child 2') ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["react"], "rules": { "react/no-children-prop": "error" } } ``` ```bash [CLI] oxlint --deny react/no-children-prop --react-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/no-class-assign.md --- url: /docs/guide/usage/linter/rules/eslint/no-class-assign.md --- ### What it does Disallow reassigning class variables. This rule can be disabled for TypeScript code, as the TypeScript compiler enforces this check. ### Why is this bad? `ClassDeclaration` creates a variable that can be re-assigned, but the re-assignment is a mistake in most cases. ### Examples Examples of **incorrect** code for this rule: ```javascript class A {} A = 0; ``` ```javascript A = 0; class A {} ``` ```javascript class A { b() { A = 0; } } ``` ```javascript let A = class A { b() { A = 0; // `let A` is shadowed by the class name. } }; ``` Examples of **correct** code for this rule: ```javascript let A = class A {}; A = 0; // A is a variable. ``` ```javascript let A = class { b() { A = 0; // A is a variable. } }; ``` ```javascript class A { b(A) { A = 0; // A is a parameter. } } ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "no-class-assign": "error" } } ``` ```bash [CLI] oxlint --deny no-class-assign ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/jest/no-commented-out-tests.md --- url: /docs/guide/usage/linter/rules/jest/no-commented-out-tests.md --- ### What it does This rule raises a warning about commented out tests. It's similar to the `no-disabled-tests` rule. ### Why is this bad? You may forget to uncomment some tests. This rule raises a warning about commented-out tests. It is generally better to skip a test if it's flaky, or remove it if it's no longer needed. ### Examples Examples of **incorrect** code for this rule: ```javascript // describe('foo', () => {}); // it('foo', () => {}); // test('foo', () => {}); // describe.skip('foo', () => {}); // it.skip('foo', () => {}); // test.skip('foo', () => {}); ``` This rule is compatible with [eslint-plugin-vitest](https://github.com/vitest-dev/eslint-plugin-vitest/blob/v1.1.9/docs/rules/no-commented-out-tests.md), to use it, add the following configuration to your `.oxlintrc.json`: ```json { "rules": { "vitest/no-commented-out-tests": "error" } } ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["jest"], "rules": { "jest/no-commented-out-tests": "error" } } ``` ```bash [CLI] oxlint --deny jest/no-commented-out-tests --jest-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/import/no-commonjs.md --- url: /docs/guide/usage/linter/rules/import/no-commonjs.md --- ### What it does Forbids the use of CommonJS `require` calls. Also forbids `module.exports` and `exports.*`. ### Why is this bad? ESM modules or Typescript uses `import` and `export` syntax instead of CommonJS syntax. This rule enforces the use of more modern module systems to improve maintainability and consistency across the codebase. ### Examples Examples of **incorrect** code for this rule: ```js var mod = require("fs"); var exports = (module.exports = {}); exports.sayHello = function () { return "Hello"; }; module.exports = "Hola"; ``` Examples of **correct** code for this rule: ```js var a = b && require("c"); if (typeof window !== "undefined") { require("somelib"); } var fs = null; try { fs = require("fs"); } catch (error) {} ``` ## Configuration This rule accepts a configuration object with the following properties: ### allowConditionalRequire type: `boolean` default: `true` When set to `true`, allows conditional `require()` calls (e.g., inside `if` statements or try-catch blocks). This is useful for places where you need to conditionally load via commonjs requires if ESM imports are not supported. ### allowPrimitiveModules type: `boolean` default: `false` If `allowPrimitiveModules` option is set to true, the following is valid: ```js module.exports = "foo"; module.exports = function rule(context) { return { /* ... */ }; }; ``` but this is still reported: ```js module.exports = { x: "y" }; exports.z = function bark() { /* ... */ }; ``` ### allowRequire type: `boolean` default: `false` If set to `true`, `require` calls are valid: ```js var mod = require("./mod"); ``` but `module.exports` is reported as usual. ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["import"], "rules": { "import/no-commonjs": "error" } } ``` ```bash [CLI] oxlint --deny import/no-commonjs --import-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/no-compare-neg-zero.md --- url: /docs/guide/usage/linter/rules/eslint/no-compare-neg-zero.md --- ### What it does Disallow comparing against `-0` ### Why is this bad? The rule should warn against code that tries to compare against `-0`, since that will not work as intended. That is, code like `x === -0` will pass for both `+0` and `-0`. The author probably intended `Object.is(x, -0)`. ### Examples Examples of **incorrect** code for this rule: ```javascript if (x === -0) { // doSomething()... } ``` ```javascript if (-0 > x) { // doSomething()... } ``` Examples of **correct** code for this rule: ```javascript if (x === 0) { // doSomething()... } ``` ```javascript if (Object.is(x, -0)) { // doSomething()... } ``` ```javascript if (0 > x) { // doSomething()... } ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "no-compare-neg-zero": "error" } } ``` ```bash [CLI] oxlint --deny no-compare-neg-zero ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/no-cond-assign.md --- url: /docs/guide/usage/linter/rules/eslint/no-cond-assign.md --- ### What it does Disallow assignment operators in conditional expressions ### Why is this bad? In conditional statements, it is very easy to mistype a comparison operator (such as `==`) as an assignment operator (such as `=`). There are valid reasons to use assignment operators in conditional statements. However, it can be difficult to tell whether a specific assignment was intentional. ### Examples Examples of **incorrect** code for this rule: ```js // Check the user's job title if ((user.jobTitle = "manager")) { // user.jobTitle is now incorrect } ``` Examples of **correct** code for this rule: ```js // Check the user's job title if (user.jobTitle === "manager") { // correctly compared `jobTitle` } ``` ## Configuration This rule accepts one of the following string values: ### `"except-parens"` Allow assignments in conditional expressions only if they are enclosed in parentheses. ### `"always"` Disallow all assignments in conditional expressions. ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "no-cond-assign": "error" } } ``` ```bash [CLI] oxlint --deny no-cond-assign ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/jest/no-conditional-expect.md --- url: /docs/guide/usage/linter/rules/jest/no-conditional-expect.md --- ### What it does This rule prevents the use of expect in conditional blocks, such as ifs & catch(s). This includes using expect in callbacks to functions named catch, which are assumed to be promises. ### Why is this bad? Jest only considers a test to have failed if it throws an error, meaning if calls to assertion functions like expect occur in conditional code such as a catch statement, tests can end up passing but not actually test anything. Additionally, conditionals tend to make tests more brittle and complex, as they increase the amount of mental thinking needed to understand what is actually being tested. ### Examples Examples of **incorrect** code for this rule: ```js it("foo", () => { doTest && expect(1).toBe(2); }); it("bar", () => { if (!skipTest) { expect(1).toEqual(2); } }); it("baz", async () => { try { await foo(); } catch (err) { expect(err).toMatchObject({ code: "MODULE_NOT_FOUND" }); } }); it("throws an error", async () => { await foo().catch((error) => expect(error).toBeInstanceOf(error)); }); ``` Examples of **correct** code for this rule: ```js it("foo", () => { expect(!value).toBe(false); }); function getValue() { if (process.env.FAIL) { return 1; } return 2; } it("foo", () => { expect(getValue()).toBe(2); }); it("validates the request", () => { try { processRequest(request); } catch { } finally { expect(validRequest).toHaveBeenCalledWith(request); } }); it("throws an error", async () => { await expect(foo).rejects.toThrow(Error); }); ``` This rule is compatible with [eslint-plugin-vitest](https://github.com/vitest-dev/eslint-plugin-vitest/blob/main/docs/rules/no-conditional-expect.md), to use it, add the following configuration to your `.oxlintrc.json`: ```json { "rules": { "vitest/no-conditional-expect": "error" } } ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["jest"], "rules": { "jest/no-conditional-expect": "error" } } ``` ```bash [CLI] oxlint --deny jest/no-conditional-expect --jest-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/jest/no-conditional-in-test.md --- url: /docs/guide/usage/linter/rules/jest/no-conditional-in-test.md --- ### What it does Disallow conditional statements in tests. ### Why is this bad? Conditional statements in tests can make the test harder to read and understand. It is better to have a single test case per test function. ### Examples Examples of **incorrect** code for this rule: ```js it("foo", () => { if (true) { doTheThing(); } }); it("bar", () => { switch (mode) { case "none": generateNone(); case "single": generateOne(); case "multiple": generateMany(); } expect(fixtures.length).toBeGreaterThan(-1); }); it("baz", async () => { const promiseValue = () => { return something instanceof Promise ? something : Promise.resolve(something); }; await expect(promiseValue()).resolves.toBe(1); }); ``` Examples of **correct** code for this rule: ```js describe("my tests", () => { if (true) { it("foo", () => { doTheThing(); }); } }); beforeEach(() => { switch (mode) { case "none": generateNone(); case "single": generateOne(); case "multiple": generateMany(); } }); it("bar", () => { expect(fixtures.length).toBeGreaterThan(-1); }); const promiseValue = (something) => { return something instanceof Promise ? something : Promise.resolve(something); }; it("baz", async () => { await expect(promiseValue()).resolves.toBe(1); }); ``` This rule is compatible with [eslint-plugin-vitest](https://github.com/vitest-dev/eslint-plugin-vitest/blob/main/docs/rules/no-conditional-in-test.md), to use it, add the following configuration to your `.oxlintrc.json`: ```json { "rules": { "vitest/no-conditional-in-test": "error" } } ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["jest"], "rules": { "jest/no-conditional-in-test": "error" } } ``` ```bash [CLI] oxlint --deny jest/no-conditional-in-test --jest-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/vitest/no-conditional-tests.md --- url: /docs/guide/usage/linter/rules/vitest/no-conditional-tests.md --- ### What it does The rule disallows the use of conditional statements within test cases to ensure that tests are deterministic and clearly readable. ### Why is this bad? Conditional statements in test cases can make tests unpredictable and harder to understand. Tests should be consistent and straightforward to ensure reliable results and maintainability. ### Examples Examples of **incorrect** code for this rule: ```js describe("my tests", () => { if (true) { it("is awesome", () => { doTheThing(); }); } }); ``` Examples of **correct** code for this rule: ```js describe("my tests", () => { it("is awesome", () => { doTheThing(); }); }); ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["vitest"], "rules": { "vitest/no-conditional-tests": "error" } } ``` ```bash [CLI] oxlint --deny vitest/no-conditional-tests --vitest-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/typescript/no-confusing-non-null-assertion.md ## What it does Disallow non-null assertion in locations that may be confusing. ## Why is this bad? Using a non-null assertion (!) next to an assign or equals check (= or == or ===) creates code that is confusing as it looks similar to a not equals check (!= !==). ## Examples Examples of **incorrect** code for this rule: ```ts a! == b; // a non-null assertions(`!`) and an equals test(`==`) a !== b; // not equals test(`!==`) a! === b; // a non-null assertions(`!`) and an triple equals test(`===`) ``` Examples of **correct** code for this rule: ```ts a == b; a !== b; a === b; ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "typescript/no-confusing-non-null-assertion": "error" } } ``` ```bash [CLI] oxlint --deny typescript/no-confusing-non-null-assertion ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/jest/no-confusing-set-timeout.md --- url: /docs/guide/usage/linter/rules/jest/no-confusing-set-timeout.md --- ### What it does Disallow confusing usages of jest.setTimeout ### Why is this bad? * being called anywhere other than in global scope * being called multiple times * being called after other Jest functions like hooks, `describe`, `test`, or `it` ### Examples All of these are invalid case: ```javascript escribe("test foo", () => { jest.setTimeout(1000); it("test-description", () => { // test logic; }); }); describe("test bar", () => { it("test-description", () => { jest.setTimeout(1000); // test logic; }); }); test("foo-bar", () => { jest.setTimeout(1000); }); describe("unit test", () => { beforeEach(() => { jest.setTimeout(1000); }); }); ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["jest"], "rules": { "jest/no-confusing-set-timeout": "error" } } ``` ```bash [CLI] oxlint --deny jest/no-confusing-set-timeout --jest-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/typescript/no-confusing-void-expression.md ## What it does This rule forbids using void expressions in confusing locations such as arrow function returns. ## Why is this bad? The void operator is useful when you want to execute an expression while evaluating to undefined. However, it can be confusing when used in places where the return value is meaningful, particularly in arrow functions and conditional expressions. ## Examples Examples of **incorrect** code for this rule: ```ts // arrow function returning void expression const foo = () => void bar(); // conditional expression const result = condition ? void foo() : bar(); // void in conditional if (void foo()) { // ... } ``` Examples of **correct** code for this rule: ```ts // proper use of void void foo(); // explicit return statement const foo = () => { bar(); return; }; // statement expression foo(); // IIFE with void void (function () { console.log("immediately invoked"); })(); ``` ## Configuration This rule accepts a configuration object with the following properties: ## ignoreArrowShorthand type: `boolean` default: `false` Whether to ignore arrow function shorthand that returns void. When true, allows expressions like `() => someVoidFunction()`. ## ignoreVoidOperator type: `boolean` default: `false` Whether to ignore expressions using the void operator. When true, allows `void someExpression`. ## ignoreVoidReturningFunctions type: `boolean` default: `false` Whether to ignore calling functions that are declared to return void. When true, allows expressions like `x = voidReturningFunction()`. ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "typescript/no-confusing-void-expression": "error" } } ``` ```bash [CLI] oxlint --type-aware --deny typescript/no-confusing-void-expression ``` ::: ## References * Rule Source * Rule Source (tsgolint) --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/unicorn/no-console-spaces.md ## What it does Disallows leading/trailing space inside `console.log()` and similar methods. ## Why is this bad? The `console.log()` method and similar methods join the parameters with a space so adding a leading/trailing space to a parameter, results in two spaces being added. ## Examples Examples of **incorrect** code for this rule: ```javascript console.log("abc ", "def"); ``` Examples of **correct** code for this rule: ```javascript console.log("abc", "def"); ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "unicorn/no-console-spaces": "error" } } ``` ```bash [CLI] oxlint --deny unicorn/no-console-spaces ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/no-console.md --- url: /docs/guide/usage/linter/rules/eslint/no-console.md --- ### What it does Disallow the use of console. ### Why is this bad? In JavaScript that is designed to be executed in the browser, it’s considered a best practice to avoid using methods on console. Such messages are considered to be for debugging purposes and therefore not suitable to ship to the client. In general, calls using console should be stripped before being pushed to production. ### Examples Examples of **incorrect** code for this rule: ```javascript console.log("Log a debug level message."); console.warn("Log a warn level message."); console.error("Log an error level message."); console.log = foo(); ``` Examples of **correct** code for this rule: ```javascript // custom console Console.log("Hello world!"); ``` ## Configuration This rule accepts a configuration object with the following properties: ### allow type: `string[]` default: `[]` The `allow` option permits the given list of console methods to be used as exceptions to this rule. Say the option was configured as `{ "allow": ["info"] }` then the rule would behave as follows: Example of **incorrect** code for this option: ```javascript console.log("foo"); ``` Example of **correct** code for this option: ```javascript console.info("foo"); ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "no-console": "error" } } ``` ```bash [CLI] oxlint --deny no-console ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/no-const-assign.md --- url: /docs/guide/usage/linter/rules/eslint/no-const-assign.md --- ### What it does Disallow reassigning `const` variables. ### Why is this bad? We cannot modify variables that are declared using the `const` keyword, as it will raise a runtime error. Note that this rule is not necessary for TypeScript code, as TypeScript will already catch this as an error. ### Examples Examples of **incorrect** code for this rule: ```js const a = 0; a = 1; const b = 0; b += 1; ``` Examples of **correct** code for this rule: ```js const a = 0; console.log(a); var b = 0; b += 1; ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "no-const-assign": "error" } } ``` ```bash [CLI] oxlint --deny no-const-assign ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/oxc/no-const-enum.md --- url: /docs/guide/usage/linter/rules/oxc/no-const-enum.md --- ### What it does Disallow TypeScript `const enum` ### Why is this bad? Const enums are enums that should be inlined at use sites. Const enums are not supported by bundlers and are incompatible with the isolatedModules mode. Their use can lead to import nonexistent values (because const enums are erased). ### Examples Examples of **incorrect** code for this rule: ```ts const enum Color { Red, Green, Blue, } ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "oxc/no-const-enum": "error" } } ``` ```bash [CLI] oxlint --deny oxc/no-const-enum ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/no-constant-binary-expression.md --- url: /docs/guide/usage/linter/rules/eslint/no-constant-binary-expression.md --- ### What it does Disallow expressions where the operation doesn't affect the value ### Why is this bad? Comparisons which will always evaluate to true or false and logical expressions (`||`, `&&`, `??`) which either always short-circuit or never short-circuit are both likely indications of programmer error. These errors are especially common in complex expressions where operator precedence is easy to misjudge. Additionally, this rule detects comparisons to newly constructed objects/arrays/functions/etc. In JavaScript, where objects are compared by reference, a newly constructed object can never `===` any other value. This can be surprising for programmers coming from languages where objects are compared by value. ### Examples Examples of **incorrect** code for this rule: ```javascript // One might think this would evaluate as `a + (b ?? c)`: const x = a + b ?? c; // But it actually evaluates as `(a + b) ?? c`. Since `a + b` can never be null, // the `?? c` has no effect. // Programmers coming from a language where objects are compared by value might expect this to work: const isEmpty = x === []; // However, this will always result in `isEmpty` being `false`. ``` Examples of **correct** code for this rule: ```javascript const x = a + (b ?? c); const isEmpty = x.length === 0; ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "no-constant-binary-expression": "error" } } ``` ```bash [CLI] oxlint --deny no-constant-binary-expression ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/no-constant-condition.md --- url: /docs/guide/usage/linter/rules/eslint/no-constant-condition.md --- ### What it does Disallow constant expressions in conditions ### Why is this bad? A constant expression (for example, a literal) as a test condition might be a typo or development trigger for a specific behavior. This rule disallows constant expressions in the test condition of: * `if`, `for`, `while`, or `do...while` statement * `?`: ternary expression ### Examples Examples of **incorrect** code for this rule: ```js if (false) { doSomethingUnfinished(); } if (new Boolean(x)) { doSomethingAlways(); } if ((x ||= true)) { doSomethingAlways(); } do { doSomethingForever(); } while ((x = -1)); ``` Examples of **correct** code for this rule: ```js if (x === 0) { doSomething(); } while (typeof x === "undefined") { doSomething(); } ``` ## Configuration This rule accepts a configuration object with the following properties: ### checkLoops type: `"all" | "allExceptWhileTrue" | "none"` default: `"allExceptWhileTrue"` Configuration option to specify whether to check for constant conditions in loops. * `"all"` or `true` disallows constant expressions in loops * `"allExceptWhileTrue"` disallows constant expressions in loops except while loops with expression `true` * `"none"` or `false` allows constant expressions in loops ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "no-constant-condition": "error" } } ``` ```bash [CLI] oxlint --deny no-constant-condition ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/no-constructor-return.md --- url: /docs/guide/usage/linter/rules/eslint/no-constructor-return.md --- ### What it does Disallow returning value from constructor ### Why is this bad? In JavaScript, returning a value in the constructor of a class may be a mistake. Forbidding this pattern prevents mistakes resulting from unfamiliarity with the language or a copy-paste error. ### Examples Examples of **incorrect** code for this rule: ```js class C { constructor() { return 42; } } ``` Examples of **correct** code for this rule: ```js class C { constructor() { this.value = 42; } } ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "no-constructor-return": "error" } } ``` ```bash [CLI] oxlint --deny no-constructor-return ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/no-continue.md --- url: /docs/guide/usage/linter/rules/eslint/no-continue.md --- ### What it does Disallow `continue` statements ### Why is this bad? The continue statement terminates execution of the statements in the current iteration of the current or labeled loop, and continues execution of the loop with the next iteration. When used incorrectly it makes code less testable, less readable and less maintainable. Structured control flow statements such as if should be used instead. ### Examples Examples of **incorrect** code for this rule: ```javascript var sum = 0, i; for (i = 0; i < 10; i++) { if (i >= 5) { continue; } sum += i; } ``` Examples of **correct** code for this rule: ```javascript var sum = 0, i; for (i = 0; i < 10; i++) { if (i < 5) { sum += i; } } ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "no-continue": "error" } } ``` ```bash [CLI] oxlint --deny no-continue ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/no-control-regex.md --- url: /docs/guide/usage/linter/rules/eslint/no-control-regex.md --- ### What it does Disallows control characters and some escape sequences that match control characters in regular expressions. ### Why is this bad? Control characters are special, invisible characters in the ASCII range 0-31. These characters are rarely used in JavaScript strings so a regular expression containing elements that explicitly match these characters is most likely a mistake. ### Examples Examples of **incorrect** code for this rule: ```javascript var pattern1 = /\x00/; var pattern2 = /\x0C/; var pattern3 = /\x1F/; var pattern4 = /\u000C/; var pattern5 = /\u{C}/u; var pattern6 = new RegExp("\x0C"); // raw U+000C character in the pattern var pattern7 = new RegExp("\\x0C"); // \x0C pattern ``` Examples of **correct** code for this rule: ```javascript var pattern1 = /\x20/; var pattern2 = /\u0020/; var pattern3 = /\u{20}/u; var pattern4 = /\t/; var pattern5 = /\n/; var pattern6 = new RegExp("\x20"); var pattern7 = new RegExp("\\t"); var pattern8 = new RegExp("\\n"); ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "no-control-regex": "error" } } ``` ```bash [CLI] oxlint --deny no-control-regex ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/nextjs/no-css-tags.md --- url: /docs/guide/usage/linter/rules/nextjs/no-css-tags.md --- ### What it does Prevents manual inclusion of stylesheets using `` tags in Next.js applications. This rule checks for `` tags with `rel="stylesheet"` that reference local CSS files. ### Why is this bad? Next.js handles CSS imports automatically through its built-in CSS support. Manual stylesheet inclusion bypasses Next.js's built-in CSS optimization, prevents proper code splitting and optimization of styles, and may cause Flash of Unstyled Content (FOUC). This also breaks automatic CSS hot reloading during development. ### Examples Examples of **incorrect** code for this rule: ```jsx // Manually including local CSS file // In pages/_document.js ``` Examples of **correct** code for this rule: ```jsx // Importing CSS file directly import '../styles/global.css' // Using CSS Modules import styles from './Button.module.css' // Using external stylesheets (allowed) // Using styled-jsx ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["nextjs"], "rules": { "nextjs/no-css-tags": "error" } } ``` ```bash [CLI] oxlint --deny nextjs/no-css-tags --nextjs-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/import/no-cycle.md --- url: /docs/guide/usage/linter/rules/import/no-cycle.md --- ### What it does Ensures that there is no resolvable path back to this module via its dependencies. This includes cycles of depth 1 (imported module imports me) to an effectively infinite value, if the `maxDepth` option is not set. ### Why is this bad? Dependency cycles lead to confusing architectures where bugs become hard to find. It is common to import an `undefined` value that is caused by a cyclic dependency. ### Examples Examples of **incorrect** code for this rule: ```javascript // dep-b.js import "./dep-a.js"; export function b() { /* ... */ } ``` ```javascript // dep-a.js import { b } from "./dep-b.js"; // reported: Dependency cycle detected. export function a() { /* ... */ } ``` In this example, `dep-a.js` and `dep-b.js` import each other, creating a circular dependency, which is problematic. Examples of **correct** code for this rule: ```javascript // dep-b.js export function b() { /* ... */ } ``` ```javascript // dep-a.js import { b } from "./dep-b.js"; // no circular dependency export function a() { /* ... */ } ``` In this corrected version, `dep-b.js` no longer imports `dep-a.js`, breaking the cycle. ## Configuration This rule accepts a configuration object with the following properties: ### allowUnsafeDynamicCyclicDependency type: `boolean` default: `false` Allow cyclic dependency if there is at least one dynamic import in the chain ### ignoreExternal type: `boolean` default: `false` Ignore external modules ### ignoreTypes type: `boolean` default: `true` Ignore type-only imports ### maxDepth type: `integer` default: `4294967295` Maximum dependency depth to traverse ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["import"], "rules": { "import/no-cycle": "error" } } ``` ```bash [CLI] oxlint --deny import/no-cycle --import-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/react/no-danger-with-children.md ## What it does Disallows when a DOM element is using both `children` and `dangerouslySetInnerHTML` properties. ## Why is this bad? React will throw a warning if this rule is ignored and both `children` and `dangerouslySetInnerHTML` are used. ## Examples Examples of **incorrect** code for this rule: ```jsx
Children
; React.createElement("div", { dangerouslySetInnerHTML: { __html: "HTML" } }, "Children"); ``` Examples of **correct** code for this rule: ```jsx
Children
``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["react"], "rules": { "react/no-danger-with-children": "error" } } ``` ```bash [CLI] oxlint --deny react/no-danger-with-children --react-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/react/no-danger.md ## What it does This rule prevents the use of `dangerouslySetInnerHTML` prop. ## Why is this bad? `dangerouslySetInnerHTML` is a way to inject HTML into your React component. This is dangerous because it can easily lead to XSS vulnerabilities. ## Examples Examples of **incorrect** code for this rule: ```jsx import React from "react"; const Hello =
; ``` Examples of **correct** code for this rule: ```jsx import React from "react"; const Hello =
Hello World
; ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["react"], "rules": { "react/no-danger": "error" } } ``` ```bash [CLI] oxlint --deny react/no-danger --react-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/no-debugger.md --- url: /docs/guide/usage/linter/rules/eslint/no-debugger.md --- ### What it does Checks for usage of the `debugger` statement ### Why is this bad? `debugger` statements do not affect functionality when a debugger isn't attached. They're most commonly an accidental debugging leftover. ### Examples Examples of **incorrect** code for this rule: ```javascript async function main() { const data = await getData(); const result = complexCalculation(data); debugger; } ``` Examples of **correct** code for this rule: ```javascript async function main() { const data = await getData(); const result = complexCalculation(data); } ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "no-debugger": "error" } } ``` ```bash [CLI] oxlint --deny no-debugger ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/import/no-default-export.md --- url: /docs/guide/usage/linter/rules/import/no-default-export.md --- ### What it does Forbids a module from having default exports. This helps your editor provide better auto-import functionality, as named exports offer more explicit and predictable imports compared to default exports. ### Why is this bad? Default exports can lead to confusion, as the name of the imported value can vary based on how it's imported. This can make refactoring and auto-imports less reliable. ### Examples Examples of **incorrect** code for this rule: ```javascript export default 'bar'; const foo = 'foo'; export { foo as default } ``` Examples of **correct** code for this rule: ```javascript export const foo = "foo"; export const bar = "bar"; ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["import"], "rules": { "import/no-default-export": "error" } } ``` ```bash [CLI] oxlint --deny import/no-default-export --import-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/jsdoc/no-defaults.md --- url: /docs/guide/usage/linter/rules/jsdoc/no-defaults.md --- ### What it does This rule reports defaults being used on the relevant portion of `@param` or `@default`. It also optionally reports the presence of the square-bracketed optional arguments at all. ### Why is this bad? The rule is intended to prevent the indication of defaults on tags where this would be redundant with ES2015 default parameters. ### Examples Examples of **incorrect** code for this rule: ```javascript /** @param {number} [foo="7"] */ function quux(foo) {} ``` Examples of **correct** code for this rule: ```javascript /** @param {number} foo */ function quux(foo) {} /** @param foo */ function quux(foo) {} ``` ## Configuration This rule accepts a configuration object with the following properties: ### noOptionalParamNames type: `boolean` default: `false` If true, report the presence of optional param names (square brackets) on `@param` tags. ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["jsdoc"], "rules": { "jsdoc/no-defaults": "error" } } ``` ```bash [CLI] oxlint --deny jsdoc/no-defaults --jsdoc-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/no-delete-var.md --- url: /docs/guide/usage/linter/rules/eslint/no-delete-var.md --- ### What it does The purpose of the `delete` operator is to remove a property from an object. ### Why is this bad? Using the `delete` operator on a variable might lead to unexpected behavior. ### Examples Examples of **incorrect** code for this rule: ```javascript var x; delete x; ``` Examples of **correct** code for this rule: ```javascript var x; var y; delete y.prop; ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "no-delete-var": "error" } } ``` ```bash [CLI] oxlint --deny no-delete-var ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/vue/no-deprecated-destroyed-lifecycle.md --- url: /docs/guide/usage/linter/rules/vue/no-deprecated-destroyed-lifecycle.md --- ### What it does Disallow using deprecated `destroyed` and `beforeDestroy` lifecycle hooks in Vue.js 3.0.0+. ### Why is this bad? In Vue.js 3.0.0+, the `destroyed` and `beforeDestroy` lifecycle hooks have been renamed to `unmounted` and `beforeUnmount` respectively. Using the old names is deprecated and may cause confusion or compatibility issues. ### Examples Examples of **incorrect** code for this rule: ```vue ``` Examples of **correct** code for this rule: ```vue ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["vue"], "rules": { "vue/no-deprecated-destroyed-lifecycle": "error" } } ``` ```bash [CLI] oxlint --deny vue/no-deprecated-destroyed-lifecycle --vue-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/jest/no-deprecated-functions.md --- url: /docs/guide/usage/linter/rules/jest/no-deprecated-functions.md --- ### What it does Over the years Jest has accrued some debt in the form of functions that have either been renamed for clarity, or replaced with more powerful APIs. This rule can also autofix a number of these deprecations for you. #### `jest.resetModuleRegistry` This function was renamed to `resetModules` in Jest 15 and removed in Jest 27. #### `jest.addMatchers` This function was replaced with `expect.extend` in Jest 17 and removed in Jest 27. #### `require.requireActual` & `require.requireMock` These functions were replaced in Jest 21 and removed in Jest 26. Originally, the `requireActual` and `requireMock` functions were placed onto the `require` function. These functions were later moved onto the `jest` object in order to be easier for type checkers to handle, and their use via `require` deprecated. Finally, the release of Jest 26 saw them removed from the `require` function altogether. #### `jest.runTimersToTime` This function was renamed to `advanceTimersByTime` in Jest 22 and removed in Jest 27. #### `jest.genMockFromModule` This function was renamed to `createMockFromModule` in Jest 26, and is scheduled for removal in Jest 30. ### Why is this bad? While typically these deprecated functions are kept in the codebase for a number of majors, eventually they are removed completely. ### Examples Examples of **incorrect** code for this rule: ```javascript jest.resetModuleRegistry; // since Jest 15 jest.addMatchers; // since Jest 17 ``` ## Configuration This rule accepts a configuration object with the following properties: ### jest type: `object` Jest configuration options. #### jest.version type: `string` default: `"29"` The version of Jest being used. ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["jest"], "rules": { "jest/no-deprecated-functions": "error" } } ``` ```bash [CLI] oxlint --deny jest/no-deprecated-functions --jest-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/typescript/no-deprecated.md ## What it does Disallow using code marked as `@deprecated`. ## Why is this bad? The JSDoc `@deprecated` tag can be used to document some piece of code being deprecated. It's best to avoid using code marked as deprecated. This rule reports on any references to code marked as `@deprecated`. TypeScript recognizes the `@deprecated` tag, allowing editors to visually indicate deprecated code — usually with a strikethrough. However, TypeScript doesn't report type errors for deprecated code on its own. ## Examples Examples of **incorrect** code for this rule: ```ts /** @deprecated Use apiV2 instead. */ declare function apiV1(): Promise; declare function apiV2(): Promise; await apiV1(); // Using deprecated function import { parse } from "node:url"; // 'parse' is deprecated. Use the WHATWG URL API instead. const url = parse("/foo"); ``` Examples of **correct** code for this rule: ```ts /** @deprecated Use apiV2 instead. */ declare function apiV1(): Promise; declare function apiV2(): Promise; await apiV2(); // Using non-deprecated function // Modern Node.js API, uses `new URL()` const url2 = new URL("/foo", "http://www.example.com"); ``` ## Configuration This rule accepts a configuration object with the following properties: ## allow type: `array` default: `[]` An array of type or value specifiers that are allowed to be used even if deprecated. Use this to allow specific deprecated APIs that you intentionally want to continue using. ### allow\[n] type: `string` Type or value specifier for matching specific declarations Supports four types of specifiers: 1. **String specifier** (deprecated): Universal match by name ```json "Promise" ``` 1. **File specifier**: Match types/values declared in local files ```json { "from": "file", "name": "MyType" } { "from": "file", "name": ["Type1", "Type2"] } { "from": "file", "name": "MyType", "path": "./types.ts" } ``` 1. **Lib specifier**: Match TypeScript built-in lib types ```json { "from": "lib", "name": "Promise" } { "from": "lib", "name": ["Promise", "PromiseLike"] } ``` 1. **Package specifier**: Match types/values from npm packages ```json { "from": "package", "name": "Observable", "package": "rxjs" } { "from": "package", "name": ["Observable", "Subject"], "package": "rxjs" } ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "typescript/no-deprecated": "error" } } ``` ```bash [CLI] oxlint --type-aware --deny typescript/no-deprecated ``` ::: ## References * Rule Source * Rule Source (tsgolint) --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/react/no-did-mount-set-state.md ## What it does Disallows using `setState` in the `componentDidMount` lifecycle method. This rule is not relevant for function components, and so can potentially be disabled for modern React codebases. ## Why is this bad? Updating the state after a component mount will trigger a second `render()` call and can lead to property/layout thrashing. This can cause performance issues and unexpected behavior. ## Examples Examples of **incorrect** code for this rule: ```jsx var Hello = createReactClass({ componentDidMount: function () { this.setState({ name: this.props.name.toUpperCase(), }); }, render: function () { return
Hello {this.state.name}
; }, }); ``` Examples of **correct** code for this rule: ```jsx var Hello = createReactClass({ componentDidMount: function () { this.onMount(function callback(newName) { this.setState({ name: newName, }); }); }, render: function () { return
Hello {this.state.name}
; }, }); ``` ## Configuration This rule accepts one of the following string values: ## `"allowed"` Allow `setState` calls in nested functions within `componentDidMount`, the default behavior. ## `"disallow-in-func"` When set, also disallows `setState` calls in nested functions within `componentDidMount`. ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["react"], "rules": { "react/no-did-mount-set-state": "error" } } ``` ```bash [CLI] oxlint --deny react/no-did-mount-set-state --react-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/react/no-direct-mutation-state.md ## What it does This rule forbids the direct mutation of `this.state` in React components. Note that this rule only applies to class components, it does not apply to function components. For modern React codebases, this rule may not be necessary or relevant. ## Why is this bad? React components should *never* mutate `this.state` directly, as calling `setState()` afterwards may replace the mutation you made. `this.state` should be treated as if it were immutable. ## Examples Examples of **incorrect** code for this rule: ```jsx var Hello = createReactClass({ componentDidMount: function () { this.state.name = this.props.name.toUpperCase(); }, render: function () { return
Hello {this.state.name}
; }, }); class Hello extends React.Component { constructor(props) { super(props); doSomethingAsync(() => { this.state = "bad"; }); } } ``` Examples of **correct** code for this rule: ```jsx var Hello = createReactClass({ componentDidMount: function() { this.setState({ name: this.props.name.toUpperCase(); }); }, render: function() { return
Hello {this.state.name}
; } }); class Hello extends React.Component { constructor(props) { super(props) this.state = { foo: 'bar', } } } ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["react"], "rules": { "react/no-direct-mutation-state": "error" } } ``` ```bash [CLI] oxlint --deny react/no-direct-mutation-state --react-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/jest/no-disabled-tests.md --- url: /docs/guide/usage/linter/rules/jest/no-disabled-tests.md --- ### What it does This rule raises a warning about disabled tests. ### Why is this bad? Jest has a feature that allows you to temporarily mark tests as disabled. This feature is often helpful while debugging or to create placeholders for future tests. Before committing changes we may want to check that all tests are running. ### Examples ```js describe.skip("foo", () => {}); it.skip("foo", () => {}); test.skip("foo", () => {}); describe["skip"]("bar", () => {}); it["skip"]("bar", () => {}); test["skip"]("bar", () => {}); xdescribe("foo", () => {}); xit("foo", () => {}); xtest("foo", () => {}); it("bar"); test("bar"); it("foo", () => { pending(); }); ``` This rule is compatible with [eslint-plugin-vitest](https://github.com/vitest-dev/eslint-plugin-vitest/blob/v1.1.9/docs/rules/no-disabled-tests.md), to use it, add the following configuration to your `.oxlintrc.json`: ```json { "rules": { "vitest/no-disabled-tests": "error" } } ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["jest"], "rules": { "jest/no-disabled-tests": "error" } } ``` ```bash [CLI] oxlint --deny jest/no-disabled-tests --jest-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/jsx_a11y/no-distracting-elements.md --- url: /docs/guide/usage/linter/rules/jsx_a11y/no-distracting-elements.md --- ### What it does Enforces that no distracting elements are used. ### Why is this bad? Elements that can be visually distracting can cause accessibility issues with visually impaired users. Such elements are most likely deprecated, and should be avoided. By default, `` and `` elements are visually distracting and can trigger vestibular disorders. ### Examples Examples of **incorrect** code for this rule: ```jsx ``` Examples of **correct** code for this rule: ```jsx
``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["jsx-a11y"], "rules": { "jsx-a11y/no-distracting-elements": "error" } } ``` ```bash [CLI] oxlint --deny jsx-a11y/no-distracting-elements --jsx-a11y-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/no-div-regex.md --- url: /docs/guide/usage/linter/rules/eslint/no-div-regex.md --- ### What it does Disallow equal signs explicitly at the beginning of regular expressions. ### Why is this bad? Characters /= at the beginning of a regular expression literal can be confused with a division assignment operator. ### Examples Examples of **incorrect** code for this rule: ```javascript function bar() { return /=foo/; } ``` Examples of **correct** code for this rule: ```javascript function bar() { return /[=]foo/; } ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "no-div-regex": "error" } } ``` ```bash [CLI] oxlint --deny no-div-regex ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/unicorn/no-document-cookie.md ## What it does Disallow direct use of [`document.cookie`](https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie). ## Why is this bad? It's not recommended to use [`document.cookie`](https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie) directly as it's easy to get the string wrong. Instead, you should use the [Cookie Store API](https://developer.mozilla.org/en-US/docs/Web/API/Cookie_Store_API) or a [cookie library](https://www.npmjs.com/search?q=cookie). ## Examples Examples of **incorrect** code for this rule: ```javascript document.cookie = "foo=bar" + "; Path=/" + "; Domain=example.com" + "; expires=Fri, 31 Dec 9999 23:59:59 GMT" + "; Secure"; ``` Examples of **correct** code for this rule: ```javascript async function storeCookies() { await cookieStore.set({ name: "foo", value: "bar", expires: Date.now() + 24 * 60 * 60 * 1000, domain: "example.com", }); } ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "unicorn/no-document-cookie": "error" } } ``` ```bash [CLI] oxlint --deny unicorn/no-document-cookie ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/nextjs/no-document-import-in-page.md --- url: /docs/guide/usage/linter/rules/nextjs/no-document-import-in-page.md --- ### What it does Prevent importing `next/document` outside of `pages/_document.js`. ### Why is this bad? Importing `next/document` outside of `pages/_document.js` can cause unexpected issues in your Next.js application. ### Examples Examples of **incorrect** code for this rule: ```jsx // `components/MyDocument.jsx` import Document from "next/document"; class MyDocument extends Document { //... } export default MyDocument; ``` Examples of **correct** code for this rule: ```jsx // `pages/_document.jsx` import Document from "next/document"; class MyDocument extends Document { //... } export default MyDocument; ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["nextjs"], "rules": { "nextjs/no-document-import-in-page": "error" } } ``` ```bash [CLI] oxlint --deny nextjs/no-document-import-in-page --nextjs-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/jest/no-done-callback.md --- url: /docs/guide/usage/linter/rules/jest/no-done-callback.md --- ### What it does This rule checks the function parameter of hooks & tests for use of the done argument, suggesting you return a promise instead. ### Why is this bad? When calling asynchronous code in hooks and tests, jest needs to know when the asynchronous work is complete to progress the current run. Originally the most common pattern to achieve this was to use callbacks: ```javascript test("the data is peanut butter", (done) => { function callback(data) { try { expect(data).toBe("peanut butter"); done(); } catch (error) { done(error); } } fetchData(callback); }); ``` This can be very error-prone however, as it requires careful understanding of how assertions work in tests or otherwise tests won't behave as expected. ### Examples Examples of **incorrect** code for this rule: ```javascript beforeEach((done) => { // ... }); test("myFunction()", (done) => { // ... }); test("myFunction()", function (done) { // ... }); ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["jest"], "rules": { "jest/no-done-callback": "error" } } ``` ```bash [CLI] oxlint --deny jest/no-done-callback --jest-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/no-dupe-class-members.md --- url: /docs/guide/usage/linter/rules/eslint/no-dupe-class-members.md --- ### What it does Disallow duplicate class members. This rule can be disabled for TypeScript code, as the TypeScript compiler enforces this check. ### Why is this bad? If there are declarations of the same name in class members, the last declaration overwrites other declarations silently. It can cause unexpected behaviors. ### Examples Examples of **incorrect** code for this rule: ```javascript class A { foo() { console.log("foo"); } foo = 123; } let a = new A(); a.foo(); // Uncaught TypeError: a.foo is not a function ``` Examples of **correct** code for this rule: ```javascript class A { foo() { console.log("foo"); } } let a = new A(); a.foo(); ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "no-dupe-class-members": "error" } } ``` ```bash [CLI] oxlint --deny no-dupe-class-members ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/no-dupe-else-if.md --- url: /docs/guide/usage/linter/rules/eslint/no-dupe-else-if.md --- ### What it does Disallow duplicate conditions in if-else-if chains ### Why is this bad? if-else-if chains are commonly used when there is a need to execute only one branch (or at most one branch) out of several possible branches, based on certain conditions. Two identical test conditions in the same chain are almost always a mistake in the code. Unless there are side effects in the expressions, a duplicate will evaluate to the same true or false value as the identical expression earlier in the chain, meaning that its branch can never execute. ### Examples Examples of **incorrect** code for this rule: ```javascript if (a) { foo(); } else if (b) { bar(); } else if (b) { baz(); } ``` ```javascript if (a || b) { foo(); } else if (a) { bar(); } ``` ```javascript if (n === 1) { foo(); } else if (n === 2) { bar(); } else if (n === 3) { baz(); } else if (n === 2) { quux(); } else if (n === 5) { quuux(); } ``` Examples of **correct** code for this rule: ```javascript if (a) { foo(); } else if (b) { bar(); } else if (c) { baz(); } ``` ```javascript if (a || b) { foo(); } else if (c) { bar(); } ``` ```javascript if (n === 1) { foo(); } else if (n === 2) { bar(); } else if (n === 3) { baz(); } else if (n === 4) { quux(); } else if (n === 5) { quuux(); } ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "no-dupe-else-if": "error" } } ``` ```bash [CLI] oxlint --deny no-dupe-else-if ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/no-dupe-keys.md --- url: /docs/guide/usage/linter/rules/eslint/no-dupe-keys.md --- ### What it does Disallow duplicate keys in object literals. This rule can be disabled for TypeScript code, as the TypeScript compiler enforces this check. ### Why is this bad? Multiple properties with the same key in object literals can cause unexpected behavior in your application. ### Examples Examples of **incorrect** code for this rule: ```js var foo = { bar: "baz", bar: "qux", }; var foo = { bar: "baz", bar: "qux", }; var foo = { 0x1: "baz", 1: "qux", }; ``` Examples of **correct** code for this rule: ```js var foo = { bar: "baz", qux: "qux", }; ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "no-dupe-keys": "error" } } ``` ```bash [CLI] oxlint --deny no-dupe-keys ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/no-duplicate-case.md --- url: /docs/guide/usage/linter/rules/eslint/no-duplicate-case.md --- ### What it does Disallow duplicate case labels ### Why is this bad? If a switch statement has duplicate test expressions in case clauses, it is likely that a programmer copied a case clause but forgot to change the test expression. ### Examples Examples of **incorrect** code for this rule: ```js var a = 1, one = 1; switch (a) { case 1: break; case 2: break; case 1: // duplicate test expression break; default: break; } switch (a) { case one: break; case 2: break; case one: // duplicate test expression break; default: break; } ``` Examples of **correct** code for this rule: ```js var a = 1, one = 1; switch (a) { case 1: break; case 2: break; default: break; } switch (a) { case "1": break; case "2": break; default: break; } ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "no-duplicate-case": "error" } } ``` ```bash [CLI] oxlint --deny no-duplicate-case ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/typescript/no-duplicate-enum-values.md ## What it does Disallow duplicate enum member values. ## Why is this bad? Although TypeScript supports duplicate enum member values, people usually expect members to have unique values within the same enum. Duplicate values can lead to bugs that are hard to track down. ## Examples This rule disallows defining an enum with multiple members initialized to the same value. Members without initializers will not be checked. Example of **incorrect** code: ```ts enum E { A = 0, B = 0, } ``` ```ts enum E { A = "A", B = "A", } ``` Example of **correct** code: ```ts enum E { A = 0, B = 1, } ``` ```ts enum E { A = "A", B = "B", } ``` ```ts enum E { A, B, } ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "typescript/no-duplicate-enum-values": "error" } } ``` ```bash [CLI] oxlint --deny typescript/no-duplicate-enum-values ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/jest/no-duplicate-hooks.md --- url: /docs/guide/usage/linter/rules/jest/no-duplicate-hooks.md --- ### What it does Disallows duplicate hooks in describe blocks. ### Why is this bad? Having duplicate hooks in a describe block can lead to confusion and unexpected behavior. When multiple hooks of the same type exist, they all execute in order, which can make it difficult to understand the test setup flow and may result in redundant or conflicting operations. This makes tests harder to maintain and debug. ### Examples Examples of **incorrect** code for this rule: ```javascript describe("foo", () => { beforeEach(() => { // some setup }); beforeEach(() => { // some setup }); test("foo_test", () => { // some test }); }); // Nested describe scenario describe("foo", () => { beforeEach(() => { // some setup }); test("foo_test", () => { // some test }); describe("bar", () => { test("bar_test", () => { afterAll(() => { // some teardown }); afterAll(() => { // some teardown }); }); }); }); ``` Examples of **correct** code for this rule: ```javascript describe("foo", () => { beforeEach(() => { // some setup }); test("foo_test", () => { // some test }); }); // Nested describe scenario describe("foo", () => { beforeEach(() => { // some setup }); test("foo_test", () => { // some test }); describe("bar", () => { test("bar_test", () => { beforeEach(() => { // some setup }); }); }); }); ``` This rule is compatible with [eslint-plugin-vitest](https://github.com/vitest-dev/eslint-plugin-vitest/blob/main/docs/rules/no-duplicate-hooks.md), to use it, add the following configuration to your `.oxlintrc.json`: ```json { "rules": { "vitest/no-duplicate-hooks": "error" } } ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["jest"], "rules": { "jest/no-duplicate-hooks": "error" } } ``` ```bash [CLI] oxlint --deny jest/no-duplicate-hooks --jest-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/no-duplicate-imports.md --- url: /docs/guide/usage/linter/rules/eslint/no-duplicate-imports.md --- ### What it does Disallow duplicate module imports. ### Why is this bad? Using a single import statement per module will make the code clearer because you can see everything being imported from that module on one line. ### Examples Examples of **incorrect** code for this rule: In the following example the module import on line 1 is repeated on line 3. These can be combined to make the list of imports more succinct. ```js import { merge } from "module"; import something from "another-module"; import { find } from "module"; ``` Examples of **correct** code for this rule: ```js import { merge, find } from "module"; import something from "another-module"; ``` ## Configuration This rule accepts a configuration object with the following properties: ### allowSeparateTypeImports type: `boolean` default: `false` When `true`, imports with only type specifiers (inline types or type imports) are considered separate from imports with value specifiers, so they can be imported from the same module on separate import statements. Examples of **correct** code when `allowSeparateTypeImports` is set to `true`: ```js import { foo } from "module"; import type { Bar } from "module"; ``` ```js import { type Foo } from "module"; import type { Bar } from "module"; ``` ### includeExports type: `boolean` default: `false` When `true` this rule will also look at exports to see if there is both a re-export of a module as in `export ... from 'module'` and also a standard import statement for the same module. This would count as a rule violation because there are in a sense two statements importing from the same module. Examples of **incorrect** code when `includeExports` is set to `true`: ```js import { merge } from "module"; export { find } from "module"; // re-export which is an import and an export. ``` Examples of **correct** code when `includeExports` is set to `true`: If re-exporting from an imported module, you should add the imports to the `import` statement, and export that directly, not use `export ... from`. ```js import { merge } from "lodash-es"; export { merge as lodashMerge }; ``` ```js import { merge, find } from "module"; // cannot be merged with the above import export * as something from "module"; // cannot be written differently export * from "module"; ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "no-duplicate-imports": "error" } } ``` ```bash [CLI] oxlint --deny no-duplicate-imports ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/typescript/no-duplicate-type-constituents.md ## What it does This rule disallows duplicate constituents of union or intersection types. ## Why is this bad? Duplicate constituents in union and intersection types serve no purpose and can make code harder to read. They are likely a mistake. ## Examples Examples of **incorrect** code for this rule: ```ts type T1 = "A" | "A"; type T2 = A | A | B; type T3 = { a: string } & { a: string }; type T4 = [A, A]; type T5 = "foo" | "bar" | "foo"; ``` Examples of **correct** code for this rule: ```ts type T1 = "A" | "B"; type T2 = A | B | C; type T3 = { a: string } & { b: string }; type T4 = [A, B]; type T5 = "foo" | "bar" | "baz"; ``` ## Configuration This rule accepts a configuration object with the following properties: ## ignoreIntersections type: `boolean` default: `false` Whether to ignore duplicate types in intersection types. When true, allows `type T = A & A`. ## ignoreUnions type: `boolean` default: `false` Whether to ignore duplicate types in union types. When true, allows `type T = A | A`. ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "typescript/no-duplicate-type-constituents": "error" } } ``` ```bash [CLI] oxlint --type-aware --deny typescript/no-duplicate-type-constituents ``` ::: ## References * Rule Source * Rule Source (tsgolint) --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/import/no-duplicates.md --- url: /docs/guide/usage/linter/rules/import/no-duplicates.md --- ### What it does Reports if a resolved path is imported more than once in the same module. This helps avoid unnecessary duplicate imports and keeps the code clean. ### Why is this bad? Importing the same module multiple times can lead to redundancy and unnecessary complexity. It also affects maintainability, as it might confuse developers and result in inconsistent usage of imports across the code. ### Examples Examples of **incorrect** code for this rule: ```javascript import { foo } from "./module"; import { bar } from "./module"; import a from "./module"; import { b } from "./module"; ``` Examples of **correct** code for this rule: ```typescript import { foo, bar } from "./module"; import * as a from "foo"; // separate statements for namespace imports import { b } from "foo"; import { c } from "foo"; // separate type imports, unless import type { d } from "foo"; // `prefer-inline` is true ``` ## Configuration This rule accepts a configuration object with the following properties: ### considerQueryString type: `boolean` default: `false` When set to `true`, the rule will consider the query string part of the import path when determining if imports are duplicates. This is useful when using loaders like webpack that use query strings to configure how a module should be loaded. Examples of **correct** code with this option set to `true`: ```javascript import x from "./bar?optionX"; import y from "./bar?optionY"; ``` ### preferInline type: `boolean` default: `false` When set to `true`, prefer inline type imports instead of separate type import statements for TypeScript code. Examples of **correct** code with this option set to `true`: ```typescript import { Foo, type Bar } from "./module"; ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["import"], "rules": { "import/no-duplicates": "error" } } ``` ```bash [CLI] oxlint --deny import/no-duplicates --import-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/typescript/no-dynamic-delete.md ## What it does Disallow using the delete operator on computed key expressions. ## Why is this bad? Deleting dynamically computed keys can be dangerous and in some cases not well optimized. Using the delete operator on keys that aren't runtime constants could be a sign that you're using the wrong data structures. Consider using a Map or Set if you’re using an object as a key-value collection. ## Examples Examples of **incorrect** code for this rule: ```ts const container: { [i: string]: 0 } = {}; delete container["aa" + "b"]; ``` Examples of **correct** code for this rule: ```ts const container: { [i: string]: 0 } = {}; delete container.aab; ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "typescript/no-dynamic-delete": "error" } } ``` ```bash [CLI] oxlint --deny typescript/no-dynamic-delete ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/import/no-dynamic-require.md --- url: /docs/guide/usage/linter/rules/import/no-dynamic-require.md --- ### What it does Forbids imports that use an expression for the module argument. This includes dynamically resolved paths in `require` or `import` statements. ### Why is this bad? Using expressions that are resolved at runtime in import statements makes it difficult to determine where the module is being imported from. This can complicate code navigation and hinder static analysis tools, which rely on predictable module paths for linting, bundling, and other optimizations. ### Examples Examples of **incorrect** code for this rule: ```javascript require(name); require(`../${name}`); ``` Examples of **correct** code for this rule: ```javascript require("../name"); require(`../name`); ``` ## Configuration This rule accepts a configuration object with the following properties: ### esmodule type: `boolean` default: `false` When `true`, also check `import()` expressions for dynamic module specifiers. ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["import"], "rules": { "import/no-dynamic-require": "error" } } ``` ```bash [CLI] oxlint --deny import/no-dynamic-require --import-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/no-else-return.md --- url: /docs/guide/usage/linter/rules/eslint/no-else-return.md --- ### What it does Disallow `else` blocks after `return` statements in `if` statements ### Why is this bad? If an `if` block contains a `return` statement, the `else` block becomes unnecessary. Its contents can be placed outside of the block. ```javascript function foo() { if (x) { return y; } else { return z; } } ``` This rule is aimed at highlighting an unnecessary block of code following an `if` containing a return statement. As such, it will warn when it encounters an `else` following a chain of `if`s, all of them containing a `return` statement. ### Examples #### `allowElseIf: true` Examples of **incorrect** code for this rule: ```javascript function foo1() { if (x) { return y; } else { return z; } } function foo2() { if (x) { return y; } else if (z) { return w; } else { return t; } } function foo3() { if (x) { return y; } else { var t = "foo"; } return t; } function foo4() { if (error) { return "It failed"; } else { if (loading) { return "It's still loading"; } } } // Two warnings for nested occurrences function foo5() { if (x) { if (y) { return y; } else { return x; } } else { return z; } } ``` Examples of **correct** code for this rule: ```javascript function foo1() { if (x) { return y; } return z; } function foo2() { if (x) { return y; } else if (z) { var t = "foo"; } else { return w; } } function foo3() { if (x) { if (z) { return y; } } else { return z; } } function foo4() { if (error) { return "It failed"; } else if (loading) { return "It's still loading"; } } ``` ## Configuration This rule accepts a configuration object with the following properties: ### allowElseIf type: `boolean` default: `true` Whether to allow `else if` blocks after a return statement. Examples of **incorrect** code for this rule with `allowElseIf: false`: ```javascript function foo() { if (error) { return "It failed"; } else if (loading) { return "It's still loading"; } } ``` Examples of **correct** code for this rule with `allowElseIf: false`: ```javascript function foo() { if (error) { return "It failed"; } if (loading) { return "It's still loading"; } } ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "no-else-return": "error" } } ``` ```bash [CLI] oxlint --deny no-else-return ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/no-empty-character-class.md --- url: /docs/guide/usage/linter/rules/eslint/no-empty-character-class.md --- ### What it does Disallow empty character classes in regular expressions ### Why is this bad? Because empty character classes in regular expressions do not match anything, they might be typing mistakes. ### Examples Examples of **incorrect** code for this rule: ```javascript var foo = /^abc[]/; ``` Examples of **correct** code for this rule: ```javascript var foo = /^abc/; var foo2 = /^abc[123]/; ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "no-empty-character-class": "error" } } ``` ```bash [CLI] oxlint --deny no-empty-character-class ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/unicorn/no-empty-file.md ## What it does Disallows files that do not contain any meaningful code. This includes files that consist only of: * Whitespace * Comments * Directives (e.g., `"use strict"`) * Empty statements (`;`) * Empty blocks (`{}`) * Hashbangs (`#!/usr/bin/env node`) ## Why is this bad? Files with no executable or exportable content are typically unintentional or left over from refactoring. They clutter the codebase and may confuse tooling or developers by appearing to serve a purpose when they do not. ## Examples Examples of **incorrect** code for this rule: ```js ``` ```js // Comment ``` ```js /* Comment */ ``` ```js "use strict"; ``` ```js ``` ```js { } ``` ```js #!/usr/bin/env node ``` Examples of **correct** code for this rule: ```js const x = 0; ``` ```js "use strict"; const x = 0; ``` ```js const x = 0; ``` ```js { const x = 0; } ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "unicorn/no-empty-file": "error" } } ``` ```bash [CLI] oxlint --deny unicorn/no-empty-file ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/no-empty-function.md --- url: /docs/guide/usage/linter/rules/eslint/no-empty-function.md --- ### What it does Disallows the usages of empty functions ### Why is this bad? Empty functions can reduce readability because readers need to guess whether it's intentional or not. So writing a clear comment for empty functions is a good practice. ### Options #### allow `{ type: string[], default: [] }` You may pass a list of allowed function kinds, which will allow functions of these kinds to be empty. Example: ```json { "no-empty-function": ["error", { "allow": ["functions"] }] } ``` `allow` accepts the following values: * `"functions"` * `"arrowFunctions"` * `"generatorFunctions"` * `"methods"` * `"generatorMethods"` * `"getters"` * `"setters"` * `"constructors"` * `"privateConstructors"` * `"protectedConstructors"` * `"asyncFunctions"` * `"asyncMethods"` * `"decoratedFunctions"` * `"overrideMethods"` ### Examples Examples of **incorrect** code for this rule: ```typescript function foo() {} const bar = () => {}; class Foo { constructor(); someMethod() {} set bar(value) {} } ``` Examples of **correct** code for this rule: ```typescript function foo() { // do nothing } function foo() { return; } const add = (a, b) => a + b; class Foo { // constructor body is empty, but it declares a private property named // `_name` constructor(private _name: string) {} public get name() { return this._name; } } ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "no-empty-function": "error" } } ``` ```bash [CLI] oxlint --deny no-empty-function ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/typescript/no-empty-interface.md ## What it does Disallow the declaration of empty interfaces. ## Why is this bad? An empty interface in TypeScript does very little: any non-nullable value is assignable to {}. Using an empty interface is often a sign of programmer error, such as misunderstanding the concept of {} or forgetting to fill in fields. This rule aims to ensure that only meaningful interfaces are declared in the code. ## Examples Examples of **incorrect** code for this rule: ```ts interface Foo {} interface Bar extends Foo {} ``` Examples of **correct** code for this rule: ```ts interface Foo { member: string; } interface Bar extends Foo { member: string; } ``` ## Configuration This rule accepts a configuration object with the following properties: ## allowSingleExtends type: `boolean` default: `false` When set to `true`, allows empty interfaces that extend a single interface. ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "typescript/no-empty-interface": "error" } } ``` ```bash [CLI] oxlint --deny typescript/no-empty-interface ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/import/no-empty-named-blocks.md --- url: /docs/guide/usage/linter/rules/import/no-empty-named-blocks.md --- ### What it does Enforces that named import blocks are not empty. ### Why is this bad? Empty named imports serve no practical purpose and often result from accidental deletions or tool-generated code. ### Examples Examples of **incorrect** code for this rule: ```js import {} from "mod"; import Default from "mod"; ``` Examples of **correct** code for this rule: ```js import { mod } from "mod"; import Default, { mod } from "mod"; ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["import"], "rules": { "import/no-empty-named-blocks": "error" } } ``` ```bash [CLI] oxlint --deny import/no-empty-named-blocks --import-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/typescript/no-empty-object-type.md ## What it does To avoid confusion around the `{}` type allowing any non-nullish value, this rule bans usage of the `{}` type. That includes interfaces and object type aliases with no fields. ## Why is this bad? The `{}`, or "empty object" type in TypeScript is a common source of confusion for developers unfamiliar with TypeScript's structural typing. `{}` represents any non-nullish value, including literals like 0 and "". Often, developers writing `{}` actually mean either: * object: representing any object value * unknown: representing any value at all, including null and undefined In other words, the "empty object" type {}\` really means "any value that is defined". That includes arrays, class instances, functions, and primitives such as string and symbol. Note that this rule does not report on: * `{}` as a type constituent in an intersection type (e.g. types like TypeScript's built-in `type NonNullable = T & {}`), as this can be useful in type system operations. * Interfaces that extend from multiple other interfaces. ## Examples Examples of **incorrect** code for this rule: ```ts let anyObject: {}; let anyValue: {}; interface AnyObjectA {} interface AnyValueA {} type AnyObjectB = {}; type AnyValueB = {}; ``` Examples of **correct** code for this rule: ```ts let anyObject: object; let anyValue: unknown; type AnyObjectA = object; type AnyValueA = unknown; type AnyObjectB = object; type AnyValueB = unknown; let objectWith: { property: boolean }; interface InterfaceWith { property: boolean; } type TypeWith = { property: boolean }; ``` ## Configuration This rule accepts a configuration object with the following properties: ## allowInterfaces type: `"never" | "always" | "with-single-extends"` default: `"never"` Whether to allow empty interfaces. Allowed values are: * `'always'`: to always allow interfaces with no fields * `'never'` *(default)*: to never allow interfaces with no fields * `'with-single-extends'`: to allow empty interfaces that `extend` from a single base interface Examples of **correct** code for this rule with `{ allowInterfaces: 'with-single-extends' }`: ```ts interface Base { value: boolean; } interface Derived extends Base {} ``` ## allowObjectTypes type: `"never" | "always"` default: `"never"` Whether to allow empty object type literals. Allowed values are: * `'always'`: to always allow object type literals with no fields * `'never'` *(default)*: to never allow object type literals with no fields ## allowWithName type: `string` A stringified regular expression to allow interfaces and object type aliases with the configured name. This can be useful if your existing code style includes a pattern of declaring empty types with `{}` instead of `object`. Example of **incorrect** code for this rule with `{ allowWithName: 'Props$' }`: ```ts interface InterfaceValue {} type TypeValue = {}; ``` Example of **correct** code for this rule with `{ allowWithName: 'Props$' }`: ```ts interface InterfaceProps {} type TypeProps = {}; ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "typescript/no-empty-object-type": "error" } } ``` ```bash [CLI] oxlint --deny typescript/no-empty-object-type ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/no-empty-pattern.md --- url: /docs/guide/usage/linter/rules/eslint/no-empty-pattern.md --- ### What it does Disallow empty destructuring patterns. ### Why is this bad? When using destructuring, it’s possible to create a pattern that has no effect. This happens when empty curly braces are used to the right of an embedded object destructuring pattern, such as: ```JavaScript // doesn't create any variables var {a: {}} = foo; ``` In this code, no new variables are created because a is just a location helper while the `{}` is expected to contain the variables to create, such as: ```JavaScript // creates variable b var {a: { b }} = foo; ``` In many cases, the empty object pattern is a mistake where the author intended to use a default value instead, such as: ```JavaScript // creates variable a var {a = {}} = foo; ``` The difference between these two patterns is subtle, especially because the problematic empty pattern looks just like an object literal. ### Examples of **incorrect** code for this rule: ```JavaScript var {} = foo; var [] = foo; var {a: {}} = foo; var {a: []} = foo; function foo({}) {} function foo([]) {} function foo({a: {}}) {} function foo({a: []}) {} ``` ### Examples of **correct** code for this rule: ```JavaScript var {a = {}} = foo; var {a = []} = foo; function foo({a = {}}) {} function foo({a = []}) {} ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "no-empty-pattern": "error" } } ``` ```bash [CLI] oxlint --deny no-empty-pattern ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/no-empty-static-block.md --- url: /docs/guide/usage/linter/rules/eslint/no-empty-static-block.md --- ### What it does Disallows the usages of empty static blocks ### Why is this bad? Empty block statements, while not technically errors, usually occur due to refactoring that wasn’t completed. They can cause confusion when reading code. ### Examples Examples of **incorrect** code for this rule: ```js class Foo { static {} } ``` Examples of **correct** code for this rule: ```js class Foo { static { // blocks with comments are allowed } } class Bar { static { doSomething(); } } ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "no-empty-static-block": "error" } } ``` ```bash [CLI] oxlint --deny no-empty-static-block ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/no-empty.md --- url: /docs/guide/usage/linter/rules/eslint/no-empty.md --- ### What it does Disallows empty block statements ### Why is this bad? Empty block statements, while not technically errors, usually occur due to refactoring that wasn’t completed. They can cause confusion when reading code. ### Examples Examples of **incorrect** code for this rule: ```javascript if (condition) { } ``` Examples of **correct** code for this rule: ```javascript if (condition) { throw new Error("condition should be false"); } ``` ## Configuration This rule accepts a configuration object with the following properties: ### allowEmptyCatch type: `boolean` default: `false` If set to `true`, allows an empty `catch` block without triggering the linter. ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "no-empty": "error" } } ``` ```bash [CLI] oxlint --deny no-empty ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/no-eq-null.md --- url: /docs/guide/usage/linter/rules/eslint/no-eq-null.md --- ### What it does Disallow `null` comparisons without type-checking operators. ### Why is this bad? Comparing to `null` without a type-checking operator (`==` or `!=`), can have unintended results as the comparison will evaluate to `true` when comparing to not just a `null`, but also an `undefined` value. ### Examples Examples of **incorrect** code for this rule: ```js if (foo == null) { bar(); } if (baz != null) { bar(); } ``` Examples of **correct** code for this rule: ```js if (foo === null) { bar(); } if (baz !== null) { bar(); } if (bang === undefined) { bar(); } ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "no-eq-null": "error" } } ``` ```bash [CLI] oxlint --deny no-eq-null ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/no-eval.md --- url: /docs/guide/usage/linter/rules/eslint/no-eval.md --- ### What it does Disallows referencing the `eval` function. This rule is aimed at preventing potentially dangerous, unnecessary, and slow code by disallowing the use of the `eval()` function. ### Why is this bad? JavaScript’s `eval()` function is potentially dangerous and is often misused. Using `eval()` on untrusted code can open a program up to several different injection attacks. The use of `eval()` in most contexts can be substituted for a better, safer alternative approach to solving the problem, such as using `JSON.parse()` or `Function` constructors in safer ways. ### Examples Examples of **incorrect** code for this rule: ```js const obj = { x: "foo" }, key = "x", value = eval("obj." + key); (0, eval)("const a = 0"); const foo = eval; foo("const a = 0"); this.eval("const a = 0"); ``` Examples of **correct** code for this rule: ```js const obj = { x: "foo" }, key = "x", value = obj[key]; class A { foo() { this.eval("const a = 0"); } eval() {} static { this.eval("const a = 0"); } static eval() {} } ``` ## Configuration This rule accepts a configuration object with the following properties: ### allowIndirect type: `boolean` default: `true` This `allowIndirect` option allows indirect `eval()` calls. Indirect calls to `eval`(e.g., `window['eval']`) are less dangerous than direct calls because they cannot dynamically change the scope. Indirect `eval()` calls also typically have less impact on performance compared to direct calls, as they do not invoke JavaScript's scope chain. ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "no-eval": "error" } } ``` ```bash [CLI] oxlint --deny no-eval ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/no-ex-assign.md --- url: /docs/guide/usage/linter/rules/eslint/no-ex-assign.md --- ### What it does Disallow reassigning exceptions in catch clauses ### Why is this bad? If a catch clause in a try statement accidentally (or purposely) assigns another value to the exception parameter, it is impossible to refer to the error from that point on. Since there is no arguments object to offer alternative access to this data, assignment of the parameter is absolutely destructive. ### Examples Examples of **incorrect** code for this rule: ```javascript try { // code } catch (e) { e = 10; } ``` Examples of **correct** code for this rule: ```javascript try { // code } catch (e) { let val = 10; } ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "no-ex-assign": "error" } } ``` ```bash [CLI] oxlint --deny no-ex-assign ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/typescript/no-explicit-any.md ## What it does Disallows explicit use of the `any` type. ## Why is this bad? The `any` type in TypeScript is a dangerous "escape hatch" from the type system. Using `any` disables many type checking rules and is generally best used only as a last resort or when prototyping code. This rule reports on explicit uses of the `any` keyword as a type annotation. > TypeScript's `--noImplicitAny` compiler option prevents an implied `any`, but doesn't > prevent `any` from being explicitly used the way this rule does. ## Examples Examples of **incorrect** code for this rule: ```typescript const age: any = "seventeen"; const ages: any[] = ["seventeen"]; const ages: Array = ["seventeen"]; function greet(): any {} function greet(): any[] {} function greet(): Array {} function greet(): Array> {} function greet(param: Array): string {} function greet(param: Array): Array {} ``` Examples of **correct** code for this rule: ```typescript const age: number = 17; const ages: number[] = [17]; const ages: Array = [17]; function greet(): string {} function greet(): string[] {} function greet(): Array {} function greet(): Array> {} function greet(param: Array): string {} function greet(param: Array): Array {} ``` ## Configuration This rule accepts a configuration object with the following properties: ## fixToUnknown type: `boolean` default: `false` Whether to enable auto-fixing in which the `any` type is converted to the `unknown` type. ## ignoreRestArgs type: `boolean` default: `false` Whether to ignore rest parameter arrays. ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "typescript/no-explicit-any": "error" } } ``` ```bash [CLI] oxlint --deny typescript/no-explicit-any ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/vue/no-export-in-script-setup.md --- url: /docs/guide/usage/linter/rules/vue/no-export-in-script-setup.md --- ### What it does Disallow `export` in ` ``` Examples of **correct** code for this rule: ```vue ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["vue"], "rules": { "vue/no-export-in-script-setup": "error" } } ``` ```bash [CLI] oxlint --deny vue/no-export-in-script-setup --vue-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/jest/no-export.md --- url: /docs/guide/usage/linter/rules/jest/no-export.md --- ### What it does Prevents using exports if a file has one or more tests in it. ### Why is this bad? This rule aims to eliminate duplicate runs of tests by exporting things from test files. If you import from a test file, then all the tests in that file will be run in each imported instance. so bottom line, don't export from a test, but instead move helper functions into a separate file when they need to be shared across tests. ### Examples Examples of **incorrect** code for this rule: ```javascript export function myHelper() {} describe("a test", () => { expect(1).toBe(1); }); ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["jest"], "rules": { "jest/no-export": "error" } } ``` ```bash [CLI] oxlint --deny jest/no-export --jest-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/node/no-exports-assign.md --- url: /docs/guide/usage/linter/rules/node/no-exports-assign.md --- ### What it does Disallows assignment to `exports`. ### Why is this bad? Directly using `exports = {}` can lead to confusion and potential bugs because it reassigns the `exports` object, which may break module exports. It is more predictable and clearer to use `module.exports` directly or in conjunction with `exports`. This rule is aimed at disallowing `exports = {}`, but allows `module.exports = exports = {}` to avoid conflict with `n/exports-style` rule's `allowBatchAssign` option. ### Examples Examples of **incorrect** code for this rule: ```js exports = {}; ``` Examples of **correct** code for this rule: ```js module.exports.foo = 1; exports.bar = 2; module.exports = {}; // allows `exports = {}` if along with `module.exports =` module.exports = exports = {}; exports = module.exports = {}; ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["node"], "rules": { "node/no-exports-assign": "error" } } ``` ```bash [CLI] oxlint --deny node/no-exports-assign --node-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/no-extend-native.md --- url: /docs/guide/usage/linter/rules/eslint/no-extend-native.md --- ### What it does Prevents extending native global objects such as `Object`, `String`, or `Array` with new properties. ### Why is this bad? Extending native objects can cause unexpected behavior and conflicts with other code. For example: ```js // Adding a new property, which might seem okay Object.prototype.extra = 55; // Defining a user object const users = { 1: "user1", 2: "user2", }; for (const id in users) { // This will print "extra" as well as "1" and "2": console.log(id); } ``` ### Examples Examples of **incorrect** code for this rule: ```js Object.prototype.p = 0; Object.defineProperty(Array.prototype, "p", { value: 0 }); ``` Examples of **correct** code for this rule: ```js x.prototype.p = 0; Object.defineProperty(x.prototype, "p", { value: 0 }); ``` ## Configuration This rule accepts a configuration object with the following properties: ### exceptions type: `string[]` default: `[]` A list of objects which are allowed to be exceptions to the rule. ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "no-extend-native": "error" } } ``` ```bash [CLI] oxlint --deny no-extend-native ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/no-extra-bind.md --- url: /docs/guide/usage/linter/rules/eslint/no-extra-bind.md --- ### What it does Disallow unnecessary calls to .bind() ### Why is this bad? This rule is aimed at avoiding the unnecessary use of bind() and as such will warn whenever an immediately-invoked function expression (IIFE) is using bind() and doesn’t have an appropriate this value. This rule won’t flag usage of bind() that includes function argument binding. ### Examples Examples of **incorrect** code for this rule: ```js const x = function () { foo(); }.bind(bar); const z = (() => { this.foo(); }).bind(this); ``` Examples of **correct** code for this rule: ```js const x = function () { this.foo(); }.bind(bar); const y = function (a) { return a + 1; }.bind(foo, bar); ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "no-extra-bind": "error" } } ``` ```bash [CLI] oxlint --deny no-extra-bind ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/no-extra-boolean-cast.md --- url: /docs/guide/usage/linter/rules/eslint/no-extra-boolean-cast.md --- ### What it does This rule disallows unnecessary boolean casts. ### Why is this bad? In contexts such as an if statement's test where the result of the expression will already be coerced to a Boolean, casting to a Boolean via double negation (`!!`) or a `Boolean` call is unnecessary. ### Examples Examples of **incorrect** code for this rule: ```javascript var foo = !!!bar; var foo = Boolean(!!bar); if (!!foo) { } if (Boolean(foo)) { } // with "enforceForInnerExpressions" option enabled if (!!foo || bar) { } ``` Examples of **correct** code for this rule: ```javascript var foo = !bar; var foo = Boolean(bar); if (foo) { } if (foo) { } // with "enforceForInnerExpressions" option enabled if (foo || bar) { } ``` ## Configuration This rule accepts a configuration object with the following properties: ### enforceForInnerExpressions type: `boolean` default: `false` when set to `true`, in addition to checking default contexts, checks whether extra boolean casts are present in expressions whose result is used in a boolean context. See examples below. Default is `false`, meaning that this rule by default does not warn about extra booleans cast inside inner expressions. ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "no-extra-boolean-cast": "error" } } ``` ```bash [CLI] oxlint --deny no-extra-boolean-cast ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/no-extra-label.md --- url: /docs/guide/usage/linter/rules/eslint/no-extra-label.md --- ### What it does Disallow unnecessary labels. ### Why is this bad? If a loop contains no nested loops or switches, labeling the loop is unnecessary. ```js A: while (a) { break A; } ``` You can achieve the same result by removing the label and using `break` or `continue` without a label. Probably those labels would confuse developers because they expect labels to jump to further. ### Examples Examples of **incorrect** code for this rule: ```js A: while (a) { break A; } B: for (let i = 0; i < 10; ++i) { break B; } C: switch (a) { case 0: break C; } ``` Examples of **correct** code for this rule: ```js while (a) { break; } for (let i = 0; i < 10; ++i) { break; } switch (a) { case 0: break; } A: { break A; } B: while (a) { while (b) { break B; } } C: switch (a) { case 0: while (b) { break C; } break; } ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "no-extra-label": "error" } } ``` ```bash [CLI] oxlint --deny no-extra-label ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/typescript/no-extra-non-null-assertion.md ## What it does Disallow extra non-null assertions. ## Why is this bad? The `!` non-null assertion operator in TypeScript is used to assert that a value's type does not include null or undefined. Using the operator any more than once on a single value does nothing. ## Examples Examples of **incorrect** code for this rule: ```ts const foo: { bar: number } | null = null; const bar = foo!!!.bar; ``` ```ts function foo(bar: number | undefined) { const bar: number = bar!!!; } ``` ```ts function foo(bar?: { n: number }) { return bar!?.n; } ``` Examples of **correct** code for this rule: ```ts const foo: { bar: number } | null = null; const bar = foo!.bar; ``` ```ts function foo(bar: number | undefined) { const bar: number = bar!; } ``` ```ts function foo(bar?: { n: number }) { return bar?.n; } ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "typescript/no-extra-non-null-assertion": "error" } } ``` ```bash [CLI] oxlint --deny typescript/no-extra-non-null-assertion ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/typescript/no-extraneous-class.md ## What it does This rule reports when a class has no non-static members, such as for a class used exclusively as a static namespace. This rule also reports classes that have only a constructor and no fields. Those classes can generally be replaced with a standalone function. ## Why is this bad? Users who come from a OOP paradigm may wrap their utility functions in an extra class, instead of putting them at the top level of an ECMAScript module. Doing so is generally unnecessary in JavaScript and TypeScript projects. * Wrapper classes add extra cognitive complexity to code without adding any structural improvements * Whatever would be put on them, such as utility functions, are already organized by virtue of being in a module. * As an alternative, you can `import * as ...` the module to get all of them in a single object. * IDEs can't provide as good suggestions for static class or namespace imported properties when you start typing property names * It's more difficult to statically analyze code for unused variables, etc. when they're all on the class (see: [Finding dead code (and dead types) in TypeScript](https://effectivetypescript.com/2020/10/20/tsprune/)). This rule also reports classes that have only a constructor and no fields. Those classes can generally be replaced with a standalone function. ## Examples Examples of **incorrect** code for this rule: ```ts class StaticConstants { static readonly version = 42; static isProduction() { return process.env.NODE_ENV === "production"; } } class HelloWorldLogger { constructor() { console.log("Hello, world!"); } } abstract class Foo {} ``` Examples of **correct** code for this rule: ```ts const version = 42; const isProduction = () => process.env.NODE_ENV === "production"; ``` ## Configuration This rule accepts a configuration object with the following properties: ## allowConstructorOnly type: `boolean` default: `false` Allow classes that only have a constructor. ## allowEmpty type: `boolean` default: `false` Allow empty classes. ## allowStaticOnly type: `boolean` default: `false` Allow classes with only static members. ## allowWithDecorator type: `boolean` default: `false` Allow classes with decorators. ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "typescript/no-extraneous-class": "error" } } ``` ```bash [CLI] oxlint --deny typescript/no-extraneous-class ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/no-fallthrough.md --- url: /docs/guide/usage/linter/rules/eslint/no-fallthrough.md --- ### What it does Disallow fallthrough of `case` statements This rule is aimed at eliminating unintentional fallthrough of one case to the other. As such, it flags any fallthrough scenarios that are not marked by a comment. ### Why is this bad? The switch statement in JavaScript is one of the more error-prone constructs of the language thanks in part to the ability to “fall through” from one case to the next. For example: ```js switch (foo) { case 1: doSomething(); case 2: doSomethingElse(); } ``` In this example, if `foo` is `1`, then execution will flow through both cases, as the first falls through to the second. You can prevent this by using `break`, as in this example: ```js switch (foo) { case 1: doSomething(); break; case 2: doSomethingElse(); } ``` That works fine when you don’t want a fallthrough, but what if the fallthrough is intentional, there is no way to indicate that in the language. It’s considered a best practice to always indicate when a fallthrough is intentional using a comment which matches the \`/falls?\s?through/i\`\` regular expression but isn’t a directive: ```js switch (foo) { case 1: doSomething(); // falls through case 2: doSomethingElse(); } switch (foo) { case 1: doSomething(); // fall through case 2: doSomethingElse(); } switch (foo) { case 1: doSomething(); // fallsthrough case 2: doSomethingElse(); } switch (foo) { case 1: { doSomething(); // falls through } case 2: { doSomethingElse(); } } ``` In this example, there is no confusion as to the expected behavior. It is clear that the first case is meant to fall through to the second case. ### Examples Examples of **incorrect** code for this rule: ```js switch (foo) { case 1: doSomething(); case 2: doSomething(); } ``` Examples of **correct** code for this rule: ```js switch (foo) { case 1: doSomething(); break; case 2: doSomething(); } function bar(foo) { switch (foo) { case 1: doSomething(); return; case 2: doSomething(); } } switch (foo) { case 1: doSomething(); throw new Error("Boo!"); case 2: doSomething(); } switch (foo) { case 1: case 2: doSomething(); } switch (foo) { case 1: case 2: doSomething(); } switch (foo) { case 1: doSomething(); // falls through case 2: doSomething(); } switch (foo) { case 1: { doSomething(); // falls through } case 2: { doSomethingElse(); } } ``` Note that the last case statement in these examples does not cause a warning because there is nothing to fall through into. ## Configuration This rule accepts a configuration object with the following properties: ### allowEmptyCase type: `boolean` default: `false` Whether to allow empty case clauses to fall through. ### commentPattern type: `string` Custom regex pattern to match fallthrough comments. ### reportUnusedFallthroughComment type: `boolean` default: `false` Whether to report unused fallthrough comments. ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "no-fallthrough": "error" } } ``` ```bash [CLI] oxlint --deny no-fallthrough ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/react/no-find-dom-node.md ## What it does This rule disallows the use of `findDOMNode`, which was deprecated in 2018 and removed in React 19. ## Why is this bad? `findDOMNode` is an escape hatch used to access the underlying DOM node. In most cases, use of this escape hatch is discouraged because it pierces the component abstraction. It has been deprecated for years, and was [removed from React entirely in React 19](https://react.dev/blog/2024/04/25/react-19-upgrade-guide#removed-reactdom-finddomnode). It should not be used. ## Examples Examples of **incorrect** code for this rule: ```jsx class MyComponent extends Component { componentDidMount() { findDOMNode(this).scrollIntoView(); } render() { return
; } } ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["react"], "rules": { "react/no-find-dom-node": "error" } } ``` ```bash [CLI] oxlint --deny react/no-find-dom-node --react-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/typescript/no-floating-promises.md ## What it does This rule disallows "floating" Promises in TypeScript code, which is a Promise that is created without any code to handle its resolution or rejection. This rule will report Promise-valued statements that are not treated in one of the following ways: * Calling its `.then()` with two arguments * Calling its `.catch()` with one argument * `await`ing it * `return`ing it * `void`ing it This rule also reports when an Array containing Promises is created and not properly handled. The main way to resolve this is by using one of the Promise concurrency methods to create a single Promise, then handling that according to the procedure above. These methods include: * `Promise.all()` * `Promise.allSettled()` * `Promise.any()` * `Promise.race()` ## Why is this bad? Floating Promises can cause several issues, such as improperly sequenced operations, ignored Promise rejections, and more. ## Examples Examples of **incorrect** code for this rule: ```ts const promise = new Promise((resolve, reject) => resolve("value")); promise; async function returnsPromise() { return "value"; } returnsPromise().then(() => {}); Promise.reject("value").catch(); Promise.reject("value").finally(); [1, 2, 3].map(async (x) => x + 1); ``` Examples of **correct** code for this rule: ```ts const promise = new Promise((resolve, reject) => resolve("value")); await promise; async function returnsPromise() { return "value"; } void returnsPromise(); returnsPromise().then( () => {}, () => {}, ); Promise.reject("value").catch(() => {}); await Promise.reject("value").finally(() => {}); await Promise.all([1, 2, 3].map(async (x) => x + 1)); ``` ## Configuration This rule accepts a configuration object with the following properties: ## allowForKnownSafeCalls type: `array` default: `[]` Allows specific calls to be ignored, specified as type or value specifiers. ### allowForKnownSafeCalls\[n] type: `string` Type or value specifier for matching specific declarations Supports four types of specifiers: 1. **String specifier** (deprecated): Universal match by name ```json "Promise" ``` 1. **File specifier**: Match types/values declared in local files ```json { "from": "file", "name": "MyType" } { "from": "file", "name": ["Type1", "Type2"] } { "from": "file", "name": "MyType", "path": "./types.ts" } ``` 1. **Lib specifier**: Match TypeScript built-in lib types ```json { "from": "lib", "name": "Promise" } { "from": "lib", "name": ["Promise", "PromiseLike"] } ``` 1. **Package specifier**: Match types/values from npm packages ```json { "from": "package", "name": "Observable", "package": "rxjs" } { "from": "package", "name": ["Observable", "Subject"], "package": "rxjs" } ``` ## allowForKnownSafePromises type: `array` default: `[]` Allows specific Promise types to be ignored, specified as type or value specifiers. ### allowForKnownSafePromises\[n] type: `string` Type or value specifier for matching specific declarations Supports four types of specifiers: 1. **String specifier** (deprecated): Universal match by name ```json "Promise" ``` 1. **File specifier**: Match types/values declared in local files ```json { "from": "file", "name": "MyType" } { "from": "file", "name": ["Type1", "Type2"] } { "from": "file", "name": "MyType", "path": "./types.ts" } ``` 1. **Lib specifier**: Match TypeScript built-in lib types ```json { "from": "lib", "name": "Promise" } { "from": "lib", "name": ["Promise", "PromiseLike"] } ``` 1. **Package specifier**: Match types/values from npm packages ```json { "from": "package", "name": "Observable", "package": "rxjs" } { "from": "package", "name": ["Observable", "Subject"], "package": "rxjs" } ``` ## checkThenables type: `boolean` default: `false` Check for thenable objects that are not necessarily Promises. ## ignoreIIFE type: `boolean` default: `false` Ignore immediately invoked function expressions (IIFEs). ## ignoreVoid type: `boolean` default: `true` Ignore Promises that are void expressions. ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "typescript/no-floating-promises": "error" } } ``` ```bash [CLI] oxlint --type-aware --deny typescript/no-floating-promises ``` ::: ## References * Rule Source * Rule Source (tsgolint) --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/jest/no-focused-tests.md --- url: /docs/guide/usage/linter/rules/jest/no-focused-tests.md --- ### What it does This rule reminds you to remove `.only` from your tests by raising a warning whenever you are using the exclusivity feature. ### Why is this bad? Jest has a feature that allows you to focus tests by appending `.only` or prepending `f` to a test-suite or a test-case. This feature is really helpful to debug a failing test, so you don’t have to execute all of your tests. After you have fixed your test and before committing the changes you have to remove `.only` to ensure all tests are executed on your build system. ### Examples Examples of **incorrect** code for this rule: ```javascript describe.only("foo", () => {}); it.only("foo", () => {}); describe["only"]("bar", () => {}); it["only"]("bar", () => {}); test.only("foo", () => {}); test["only"]("bar", () => {}); fdescribe("foo", () => {}); fit("foo", () => {}); fit.each` table `(); ``` This rule is compatible with [eslint-plugin-vitest](https://github.com/vitest-dev/eslint-plugin-vitest/blob/v1.1.9/docs/rules/no-focused-tests.md), to use it, add the following configuration to your `.oxlintrc.json`: ```json { "rules": { "vitest/no-focused-tests": "error" } } ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["jest"], "rules": { "jest/no-focused-tests": "error" } } ``` ```bash [CLI] oxlint --deny jest/no-focused-tests --jest-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/typescript/no-for-in-array.md ## What it does This rule disallows iterating over an array with a for-in loop. ## Why is this bad? A for-in loop iterates over the enumerable properties of an object, which includes the array indices, but also includes any enumerable properties added to the array prototype or the array instance. This is almost never what you want when iterating over an array. ## Examples Examples of **incorrect** code for this rule: ```ts const arr = [1, 2, 3]; for (const i in arr) { console.log(arr[i]); } for (const i in arr) { console.log(i, arr[i]); } ``` Examples of **correct** code for this rule: ```ts const arr = [1, 2, 3]; // Use for-of to iterate over array values for (const value of arr) { console.log(value); } // Use regular for loop with index for (let i = 0; i < arr.length; i++) { console.log(i, arr[i]); } // Use forEach arr.forEach((value, index) => { console.log(index, value); }); // for-in is fine for objects const obj = { a: 1, b: 2 }; for (const key in obj) { console.log(key, obj[key]); } ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "typescript/no-for-in-array": "error" } } ``` ```bash [CLI] oxlint --type-aware --deny typescript/no-for-in-array ``` ::: ## References * Rule Source * Rule Source (tsgolint) --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/no-func-assign.md --- url: /docs/guide/usage/linter/rules/eslint/no-func-assign.md --- ### What it does Disallow reassigning `function` declarations. This rule can be disabled for TypeScript code, as the TypeScript compiler enforces this check. ### Why is this bad? Overwriting/reassigning a function written as a FunctionDeclaration is often indicative of a mistake or issue. ### Examples Examples of **incorrect** code for this rule: ```javascript function foo() {} foo = bar; ``` ```javascript function foo() { foo = bar; } ``` ```javascript let a = function hello() { hello = 123; }; ``` Examples of **correct** code for this rule: ```javascript let foo = function () {}; foo = bar; ``` ```javascript function baz(baz) { // `baz` is shadowed. baz = bar; } ``` ``` function qux() { const qux = bar; // `qux` is shadowed. } ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "no-func-assign": "error" } } ``` ```bash [CLI] oxlint --deny no-func-assign ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/no-global-assign.md --- url: /docs/guide/usage/linter/rules/eslint/no-global-assign.md --- ### What it does Disallow modifications to read-only global variables. ### Why is this bad? In almost all cases, you don't want to assign a value to these global variables as doing so could result in losing access to important functionality. ### Examples Examples of **incorrect** code for this rule: ```javascript Object = null; ``` ## Configuration This rule accepts a configuration object with the following properties: ### exceptions type: `string[]` default: `[]` List of global variable names to exclude from this rule. Globals listed here can be assigned to without triggering warnings. ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "no-global-assign": "error" } } ``` ```bash [CLI] oxlint --deny no-global-assign ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/nextjs/no-head-element.md --- url: /docs/guide/usage/linter/rules/nextjs/no-head-element.md --- ### What it does Prevents the usage of the native `` element inside a Next.js application. ### Why is this bad? A `` element can cause unexpected behavior in a Next.js application. Use Next.js' built-in `next/head` component instead. ### Examples Examples of **incorrect** code for this rule: ```jsx function Index() { return ( <> My page title ); } export default Index; ``` Examples of **correct** code for this rule: ```jsx import Head from "next/head"; function Index() { return ( <> My page title ); } export default Index; ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["nextjs"], "rules": { "nextjs/no-head-element": "error" } } ``` ```bash [CLI] oxlint --deny nextjs/no-head-element --nextjs-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/unicorn/no-hex-escape.md ## What it does Enforces a convention of using [Unicode escapes](https://mathiasbynens.be/notes/javascript-escapes#unicode) instead of [hexadecimal escapes](https://mathiasbynens.be/notes/javascript-escapes#hexadecimal) for consistency and clarity. ## Why is this bad? ## Examples Examples of **incorrect** code for this rule: ```javascript const foo = "\x1B"; const foo = `\x1B${bar}`; ``` Examples of **correct** code for this rule: ```javascript const foo = "\u001B"; const foo = `\u001B${bar}`; ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "unicorn/no-hex-escape": "error" } } ``` ```bash [CLI] oxlint --deny unicorn/no-hex-escape ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/jest/no-hooks.md --- url: /docs/guide/usage/linter/rules/jest/no-hooks.md --- ### What it does Disallows Jest setup and teardown hooks, such as `beforeAll`. ### Why is this bad? Jest provides global functions for setup and teardown tasks, which are called before/after each test case and each test suite. The use of these hooks promotes shared state between tests. This rule reports for the following function calls: * `beforeAll` * `beforeEach` * `afterAll` * `afterEach` ### Examples Examples of **incorrect** code for this rule: ```javascript function setupFoo(options) { /* ... */ } function setupBar(options) { /* ... */ } describe("foo", () => { let foo; beforeEach(() => { foo = setupFoo(); }); afterEach(() => { foo = null; }); it("does something", () => { expect(foo.doesSomething()).toBe(true); }); describe("with bar", () => { let bar; beforeEach(() => { bar = setupBar(); }); afterEach(() => { bar = null; }); it("does something with bar", () => { expect(foo.doesSomething(bar)).toBe(true); }); }); }); ``` This rule is compatible with [eslint-plugin-vitest](https://github.com/vitest-dev/eslint-plugin-vitest/blob/main/docs/rules/no-hooks.md), to use it, add the following configuration to your `.oxlintrc.json`: ```json { "rules": { "vitest/no-hooks": "error" } } ``` ## Configuration This rule accepts a configuration object with the following properties: ### allow type: `string[]` default: `[]` An array of hook function names that are permitted for use. ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["jest"], "rules": { "jest/no-hooks": "error" } } ``` ```bash [CLI] oxlint --deny jest/no-hooks --jest-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/nextjs/no-html-link-for-pages.md --- url: /docs/guide/usage/linter/rules/nextjs/no-html-link-for-pages.md --- ### What it does Prevents the usage of `` elements to navigate between Next.js pages. ### Why is this bad? Using `` elements for internal navigation in Next.js applications can cause: * Full page reloads instead of client-side navigation * Loss of application state * Slower navigation performance * Broken prefetching capabilities Next.js provides the `` component from `next/link` for client-side navigation between pages, which provides better performance and user experience. ### Examples Examples of **incorrect** code for this rule: ```jsx function HomePage() { return ( ); } ``` Examples of **correct** code for this rule: ```jsx import Link from "next/link"; function HomePage() { return (
About Us Contact
); } ``` External links are allowed: ```jsx function HomePage() { return ( ); } ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["nextjs"], "rules": { "nextjs/no-html-link-for-pages": "error" } } ``` ```bash [CLI] oxlint --deny nextjs/no-html-link-for-pages --nextjs-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/jest/no-identical-title.md --- url: /docs/guide/usage/linter/rules/jest/no-identical-title.md --- ### What it does This rule looks at the title of every test and test suite. It will report when two test suites or two test cases at the same level of a test suite have the same title. ### Why is this bad? Having identical titles for two different tests or test suites may create confusion. For example, when a test with the same title as another test in the same test suite fails, it is harder to know which one failed and thus harder to fix. ### Examples Examples of **incorrect** code for this rule: ```javascript describe("baz", () => { //... }); describe("baz", () => { // Has the same title as a previous test suite // ... }); ``` This rule is compatible with [eslint-plugin-vitest](https://github.com/vitest-dev/eslint-plugin-vitest/blob/v1.1.9/docs/rules/no-identical-title.md), to use it, add the following configuration to your `.oxlintrc.json`: ```json { "rules": { "vitest/no-identical-title": "error" } } ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["jest"], "rules": { "jest/no-identical-title": "error" } } ``` ```bash [CLI] oxlint --deny jest/no-identical-title --jest-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/nextjs/no-img-element.md --- url: /docs/guide/usage/linter/rules/nextjs/no-img-element.md --- ### What it does Prevent the usage of `` element due to slower [LCP](https://nextjs.org/learn/seo/lcp) and higher bandwidth. ### Why is this bad? `` elements are not optimized for performance and can result in slower LCP and higher bandwidth. Using [``](https://nextjs.org/docs/pages/api-reference/components/image) from `next/image` will automatically optimize images and serve them as static assets. ### Examples Examples of **incorrect** code for this rule: ```javascript export function MyComponent() { return (
Test picture
); } ``` Examples of **correct** code for this rule: ```javascript import Image from "next/image"; import testImage from "./test.png"; export function MyComponent() { return (
Test picture
); } ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["nextjs"], "rules": { "nextjs/no-img-element": "error" } } ``` ```bash [CLI] oxlint --deny nextjs/no-img-element --nextjs-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/unicorn/no-immediate-mutation.md ## What it does Disallows mutating a variable immediately after initialization. ## Why is this bad? When you initialize a variable and immediately mutate it, it's cleaner to include the mutation in the initialization. This makes the code more readable and reduces the number of statements. ## Examples Examples of **incorrect** code for this rule: ```js const array = [1, 2]; array.push(3); const object = { foo: 1 }; object.bar = 2; const set = new Set([1, 2]); set.add(3); const map = new Map([["foo", 1]]); map.set("bar", 2); ``` Examples of **correct** code for this rule: ```js const array = [1, 2, 3]; const object = { foo: 1, bar: 2 }; const set = new Set([1, 2, 3]); const map = new Map([ ["foo", 1], ["bar", 2], ]); ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "unicorn/no-immediate-mutation": "error" } } ``` ```bash [CLI] oxlint --deny unicorn/no-immediate-mutation ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/no-implicit-coercion.md --- url: /docs/guide/usage/linter/rules/eslint/no-implicit-coercion.md --- ### What it does Disallows shorthand type conversions using operators like `!!`, `+`, `""+ `, etc. ### Why is this bad? Implicit type coercions using operators can be less clear than using explicit type conversion functions like `Boolean()`, `Number()`, and `String()`. Using explicit conversions makes the intent clearer and the code more readable. ### Examples Examples of **incorrect** code for this rule: ```javascript var b = !!foo; var n = +foo; var s = "" + foo; ``` Examples of **correct** code for this rule: ```javascript var b = Boolean(foo); var n = Number(foo); var s = String(foo); ``` ## Configuration This rule accepts a configuration object with the following properties: ### allow type: `string[]` List of operators to allow. Valid values: `"!!"`, `"~"`, `"+"`, `"-"`, `"- -"`, `"*"` ### boolean type: `boolean` default: `true` When `true`, warns on implicit boolean coercion (e.g., `!!foo`). ### disallowTemplateShorthand type: `boolean` default: `false` When `true`, disallows using template literals for string coercion (e.g., `` `${foo}` ``). ### number type: `boolean` default: `true` When `true`, warns on implicit number coercion (e.g., `+foo`). ### string type: `boolean` default: `true` When `true`, warns on implicit string coercion (e.g., `"" + foo`). ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "no-implicit-coercion": "error" } } ``` ```bash [CLI] oxlint --deny no-implicit-coercion ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/typescript/no-implied-eval.md ## What it does This rule disallows the use of eval-like methods. ## Why is this bad? It's considered a good practice to avoid using eval() in JavaScript. There are security and performance implications involved with doing so, which is why many linters recommend disallowing eval(). However, there are some other ways to pass a string and have it interpreted as JavaScript code that have similar concerns. ## Examples Examples of **incorrect** code for this rule: ```ts setTimeout('alert("Hi!");', 100); setInterval('alert("Hi!");', 100); setImmediate('alert("Hi!")'); window.setTimeout("count = 5", 10); window.setInterval("foo = bar", 10); const fn = new Function("a", "b", "return a + b"); ``` Examples of **correct** code for this rule: ```ts setTimeout(() => { alert("Hi!"); }, 100); setInterval(() => { alert("Hi!"); }, 100); setImmediate(() => { alert("Hi!"); }); const fn = (a: number, b: number) => a + b; ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "typescript/no-implied-eval": "error" } } ``` ```bash [CLI] oxlint --type-aware --deny typescript/no-implied-eval ``` ::: ## References * Rule Source * Rule Source (tsgolint) --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/no-import-assign.md --- url: /docs/guide/usage/linter/rules/eslint/no-import-assign.md --- ### What it does Disallow assigning to imported bindings. ### Why is this bad? The updates of imported bindings by ES Modules cause runtime errors. The TypeScript compiler generally enforces this check already. Although it should be noted that there are some cases TypeScript does not catch, such as assignments via `Object.assign`. So this rule is still useful for TypeScript code in those cases. ### Examples Examples of **incorrect** code for this rule: ```javascript import mod, { named } from "./mod.mjs"; import * as mod_ns from "./mod.mjs"; mod = 1; // ERROR: 'mod' is readonly. named = 2; // ERROR: 'named' is readonly. mod_ns.named = 3; // ERROR: The members of 'mod_ns' are readonly. mod_ns = {}; // ERROR: 'mod_ns' is readonly. // Can't extend 'mod_ns' Object.assign(mod_ns, { foo: "foo" }); // ERROR: The members of 'mod_ns' are readonly. ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "no-import-assign": "error" } } ``` ```bash [CLI] oxlint --deny no-import-assign ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/vue/no-import-compiler-macros.md --- url: /docs/guide/usage/linter/rules/vue/no-import-compiler-macros.md --- ### What it does Disallow importing Vue compiler macros. ### Why is this bad? Compiler Macros like: * `defineProps` * `defineEmits` * `defineExpose` * `withDefaults` * `defineModel` * `defineOptions` * `defineSlots` are globally available in Vue 3's ` ``` Examples of **correct** code for this rule: ```vue ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["vue"], "rules": { "vue/no-import-compiler-macros": "error" } } ``` ```bash [CLI] oxlint --deny vue/no-import-compiler-macros --vue-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/vitest/no-import-node-test.md --- url: /docs/guide/usage/linter/rules/vitest/no-import-node-test.md --- ### What it does This rule warns when `node:test` is imported (usually accidentally). With `--fix`, it will replace the import with `vitest`. ### Why is this bad? Using `node:test` instead of `vitest` can lead to inconsistent test results and missing features. `vitest` should be used for all testing to ensure compatibility and access to its full functionality. ### Examples Examples of **incorrect** code for this rule: ```javascript import { test } from "node:test"; import { expect } from "vitest"; test("foo", () => { expect(1).toBe(1); }); ``` Examples of **correct** code for this rule: ```javascript import { test, expect } from "vitest"; test("foo", () => { expect(1).toBe(1); }); ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["vitest"], "rules": { "vitest/no-import-node-test": "error" } } ``` ```bash [CLI] oxlint --deny vitest/no-import-node-test --vitest-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/typescript/no-import-type-side-effects.md ## What it does Enforce the use of top-level `import type` qualifier when an import only has specifiers with inline type qualifiers. ## Why is this bad? The `--verbatimModuleSyntax` compiler option causes TypeScript to do simple and predictable transpilation on import declarations. Namely, it completely removes import declarations with a top-level type qualifier, and it removes any import specifiers with an inline type qualifier. The latter behavior does have one potentially surprising effect in that in certain cases TS can leave behind a "side effect" import at runtime: ```ts import { type A, type B } from "mod"; ``` is transpiled to ```ts import {} from "mod"; // which is the same as import "mod"; ``` For the rare case of needing to import for side effects, this may be desirable - but for most cases you will not want to leave behind an unnecessary side effect import. ## Examples Examples of **incorrect** code for this rule: ```ts import { type A } from "mod"; import { type A as AA } from "mod"; import { type A, type B } from "mod"; import { type A as AA, type B as BB } from "mod"; ``` Examples of **correct** code for this rule: ```ts import type { A } from "mod"; import type { A as AA } from "mod"; import type { A, B } from "mod"; import type { A as AA, B as BB } from "mod"; ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "typescript/no-import-type-side-effects": "error" } } ``` ```bash [CLI] oxlint --deny typescript/no-import-type-side-effects ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/typescript/no-inferrable-types.md ## What it does Disallow explicit type declarations for variables or parameters initialized to a number, string, or boolean ## Why is this bad? Explicitly typing variables or parameters that are initialized to a literal value is unnecessary because TypeScript can infer the type from the value. ## Examples Examples of **incorrect** code for this rule: ```ts const a: number = 5; const b: string = "foo"; const c: boolean = true; const fn = (a: number = 5, b: boolean = true, c: string = "foo") => {}; ``` Examples of **correct** code for this rule: ```ts const a = 5; const b = "foo"; const c = true; const fn = (a = 5, b = true, c = "foo") => {}; ``` ## Configuration This rule accepts a configuration object with the following properties: ## ignoreParameters type: `boolean` default: `false` When set to `true`, ignores type annotations on function parameters. ## ignoreProperties type: `boolean` default: `false` When set to `true`, ignores type annotations on class properties. ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "typescript/no-inferrable-types": "error" } } ``` ```bash [CLI] oxlint --deny typescript/no-inferrable-types ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/no-inline-comments.md --- url: /docs/guide/usage/linter/rules/eslint/no-inline-comments.md --- ### What it does Disallows comments on the same line as code. ### Why is this bad? Comments placed at the end of a line of code can make code harder to read. They can easily be missed when scanning vertically, and they make lines longer. Moving comments to their own lines makes them more prominent and reduces line length. ### Examples Examples of **incorrect** code for this rule: ```js var a = 1; // inline comment var b = 2; /* another inline comment */ ``` Examples of **correct** code for this rule: ```js // comment on its own line var a = 1; /* block comment on its own line */ var b = 2; ``` ## Configuration This rule accepts a configuration object with the following properties: ### ignorePattern type: `string` A regex pattern to ignore certain inline comments. Comments matching this pattern will not be reported. Example configuration: ```json { "no-inline-comments": ["error", { "ignorePattern": "webpackChunkName" }] } ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "no-inline-comments": "error" } } ``` ```bash [CLI] oxlint --deny no-inline-comments ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/no-inner-declarations.md --- url: /docs/guide/usage/linter/rules/eslint/no-inner-declarations.md --- ### What it does Disallow variable or function declarations in nested blocks. ### Why is this bad? A variable declaration is permitted anywhere a statement can go, even nested deeply inside other blocks. This is often undesirable due to variable hoisting, and moving declarations to the root of the program or function body can increase clarity. Note that block bindings (let, const) are not hoisted and therefore they are not affected by this rule. ### Examples Examples of **incorrect** code for this rule: ```javascript if (test) { function doSomethingElse() {} } ``` Examples of **correct** code for this rule: ```javascript function doSomethingElse() {} if (test) { // your code here } ``` ## Configuration ### The 1st option type: `"functions" | "both"` Determines what type of declarations to check. #### `"functions"` Disallows function declarations in nested blocks. #### `"both"` Disallows function and var declarations in nested blocks. ### The 2nd option This option is an object with the following properties: #### blockScopedFunctions type: `"allow" | "disallow"` ##### `"allow"` Allow function declarations in nested blocks in strict mode (ES6+ behavior). ##### `"disallow"` Disallow function declarations in nested blocks regardless of strict mode. ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "no-inner-declarations": "error" } } ``` ```bash [CLI] oxlint --deny no-inner-declarations ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/unicorn/no-instanceof-array.md ## What it does Require `Array.isArray()` instead of `instanceof Array`. ## Why is this bad? The instanceof Array check doesn't work across realms/contexts, for example, frames/windows in browsers or the vm module in Node.js. ## Examples Examples of **incorrect** code for this rule: ```javascript array instanceof Array; [1, 2, 3] instanceof Array; ``` Examples of **correct** code for this rule: ```javascript Array.isArray(array); Array.isArray([1, 2, 3]); ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "unicorn/no-instanceof-array": "error" } } ``` ```bash [CLI] oxlint --deny unicorn/no-instanceof-array ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/unicorn/no-instanceof-builtins.md ## What it does Disallows the use of `instanceof` with ECMAScript built-in constructors because: * it breaks across execution contexts (`iframe`, Web Worker, Node VM, etc.); * it is often misleading (e.g. `instanceof Array` fails for a subclass); * there is always a clearer and safer alternative (`Array.isArray`, `typeof`, `Buffer.isBuffer`, …). ## Why is this bad? `instanceof` breaks across execution contexts (`iframe`, Web Worker, Node `vm`), and may give misleading results for subclasses or exotic objects. ## Examples Examples of **incorrect** code for this rule: ```javascript if (arr instanceof Array) { … } if (el instanceof HTMLElement) { … } ``` Examples of **correct** code for this rule: ```javascript if (Array.isArray(arr)) { … } if (el?.nodeType === 1) { … } ``` ## Configuration This rule accepts a configuration object with the following properties: ## exclude type: `string[]` default: `[]` Constructor names to exclude from checking. ## include type: `string[]` default: `[]` Additional constructor names to check beyond the default set. Use this to extend the rule with additional constructors. ## strategy type: `"strict" | "loose"` default: `"loose"` Controls which built-in constructors are checked. * `"loose"` (default): Only checks Array, Function, Error (if `useErrorIsError` is true), and primitive wrappers * `"strict"`: Additionally checks Error types, collections, typed arrays, and other built-in constructors ## useErrorIsError type: `boolean` default: `false` When `true`, checks `instanceof Error` and suggests using `Error.isError()` instead. Requires [the `Error.isError()` function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/isError) to be available. ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "unicorn/no-instanceof-builtins": "error" } } ``` ```bash [CLI] oxlint --deny unicorn/no-instanceof-builtins ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/jest/no-interpolation-in-snapshots.md --- url: /docs/guide/usage/linter/rules/jest/no-interpolation-in-snapshots.md --- ### What it does Prevents the use of string interpolations in snapshots. ### Why is this bad? Interpolation prevents snapshots from being updated. Instead, properties should be overloaded with a matcher by using [property matchers](https://jestjs.io/docs/en/snapshot-testing#property-matchers). ### Examples Examples of **incorrect** code for this rule: ```javascript expect(something).toMatchInlineSnapshot( `Object { property: ${interpolated} }`, ); expect(something).toMatchInlineSnapshot( { other: expect.any(Number) }, `Object { other: Any, property: ${interpolated} }`, ); expect(errorThrowingFunction).toThrowErrorMatchingInlineSnapshot(`${interpolated}`); ``` This rule is compatible with [eslint-plugin-vitest](https://github.com/vitest-dev/eslint-plugin-vitest/blob/main/docs/rules/no-interpolation-in-snapshots.md), to use it, add the following configuration to your `.oxlintrc.json`: ```json { "rules": { "vitest/no-interpolation-in-snapshots": "error" } } ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["jest"], "rules": { "jest/no-interpolation-in-snapshots": "error" } } ``` ```bash [CLI] oxlint --deny jest/no-interpolation-in-snapshots --jest-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/unicorn/no-invalid-fetch-options.md ## What it does Disallow invalid options in `fetch()` and `new Request()`. Specifically, this rule ensures that a body is not provided when the method is `GET` or `HEAD`, as it will result in a `TypeError`. ## Why is this bad? The `fetch()` function throws a `TypeError` when the method is `GET` or `HEAD` and a body is provided. This can lead to unexpected behavior and errors in your code. By disallowing such invalid options, the rule ensures that requests are correctly configured and prevents unnecessary errors. ## Examples Examples of **incorrect** code for this rule: ```javascript const response = await fetch("/", { method: "GET", body: "foo=bar" }); const request = new Request("/", { method: "GET", body: "foo=bar" }); ``` Examples of **correct** code for this rule: ```javascript const response = await fetch("/", { method: "POST", body: "foo=bar" }); const request = new Request("/", { method: "POST", body: "foo=bar" }); ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "unicorn/no-invalid-fetch-options": "error" } } ``` ```bash [CLI] oxlint --deny unicorn/no-invalid-fetch-options ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/no-invalid-regexp.md --- url: /docs/guide/usage/linter/rules/eslint/no-invalid-regexp.md --- ### What it does Disallow invalid regular expression strings in RegExp constructors. ### Why is this bad? An invalid pattern in a regular expression literal is a SyntaxError when the code is parsed, but an invalid string in RegExp constructors throws a SyntaxError only when the code is executed. ### Examples Examples of **incorrect** code for this rule: ```js RegExp("["); RegExp(".", "z"); new RegExp("\\"); ``` Examples of **correct** code for this rule: ```js RegExp("."); new RegExp(); this.RegExp("["); ``` ## Configuration This rule accepts a configuration object with the following properties: ### allowConstructorFlags type: `string[]` default: `[]` Case-sensitive array of flags that will be allowed. ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "no-invalid-regexp": "error" } } ``` ```bash [CLI] oxlint --deny no-invalid-regexp ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/unicorn/no-invalid-remove-event-listener.md ## What it does It warns when you use a non-function value as the second argument of `removeEventListener`. ## Why is this bad? The [`removeEventListener`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener) function must be called with a reference to the same function that was passed to [`addEventListener`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener). Calling `removeEventListener` with an inline function or the result of an inline `.bind()` call is indicative of an error, and won't actually remove the listener. ## Examples Examples of **incorrect** code for this rule: ```javascript el.removeEventListener("click", () => {}); el.removeEventListener("click", function () {}); ``` Examples of **correct** code for this rule: ```javascript el.removeEventListener("click", handler); el.removeEventListener("click", handler.bind(this)); ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "unicorn/no-invalid-remove-event-listener": "error" } } ``` ```bash [CLI] oxlint --deny unicorn/no-invalid-remove-event-listener ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/no-irregular-whitespace.md --- url: /docs/guide/usage/linter/rules/eslint/no-irregular-whitespace.md --- ### What it does Disallows the use of irregular whitespace characters in the code. ### Why is this bad? Irregular whitespace characters are invisible to most editors and can cause unexpected behavior, making code harder to debug and maintain. They can also cause issues with code formatting and parsing. ### Examples Examples of **incorrect** code for this rule: ```javascript // Contains irregular whitespace characters (invisible) function example() { var foo = "bar"; // irregular whitespace before 'bar' } ``` Examples of **correct** code for this rule: ```javascript function example() { var foo = "bar"; // regular spaces only } ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "no-irregular-whitespace": "error" } } ``` ```bash [CLI] oxlint --deny no-irregular-whitespace ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/react/no-is-mounted.md ## What it does This rule prevents using `isMounted` in class components. ## Why is this bad? `isMounted` is an anti-pattern, and is not available when using classes or function components. ## Examples Examples of **incorrect** code for this rule: ```jsx class Hello extends React.Component { someMethod() { if (!this.isMounted()) { return; } } render() { return
Hello
; } } ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["react"], "rules": { "react/no-is-mounted": "error" } } ``` ```bash [CLI] oxlint --deny react/no-is-mounted --react-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/no-iterator.md --- url: /docs/guide/usage/linter/rules/eslint/no-iterator.md --- ### What it does Disallow the use of the `__iterator__` property ### Why is this bad? The `__iterator__` property was a SpiderMonkey extension to JavaScript that could be used to create custom iterators that are compatible with JavaScript’s for in and for each constructs. However, this property is now obsolete, so it should not be used. Here’s an example of how this used to work: ```js Foo.prototype.__iterator__ = function () { return new FooIterator(this); }; ``` ### Examples Examples of **incorrect** code for this rule: ```javascript Foo.prototype.__iterator__ = function () { return new FooIterator(this); }; foo.__iterator__ = function () {}; foo["__iterator__"] = function () {}; ``` Examples of **correct** code for this rule: ```js const __iterator__ = 42; // not using the __iterator__ property Foo.prototype[Symbol.iterator] = function () { return new FooIterator(this); }; ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "no-iterator": "error" } } ``` ```bash [CLI] oxlint --deny no-iterator ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/jest/no-jasmine-globals.md --- url: /docs/guide/usage/linter/rules/jest/no-jasmine-globals.md --- ### What it does This rule reports on any usage of Jasmine globals, which is not ported to Jest, and suggests alternatives from Jest's own API. ### Why is this bad? When migrating from Jasmine to Jest, relying on Jasmine-specific globals creates compatibility issues and prevents taking advantage of Jest's improved testing features and better error reporting. ### Examples Examples of **incorrect** code for this rule: ```javascript jasmine.DEFAULT_TIMEOUT_INTERVAL = 5000; test("my test", () => { pending(); }); test("my test", () => { jasmine.createSpy(); }); ``` Examples of **correct** code for this rule: ```javascript jest.setTimeout(5000); test("my test", () => { // Use test.skip() instead of pending() }); test.skip("my test", () => { // Skipped test }); test("my test", () => { jest.fn(); // Use jest.fn() instead of jasmine.createSpy() }); ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["jest"], "rules": { "jest/no-jasmine-globals": "error" } } ``` ```bash [CLI] oxlint --deny jest/no-jasmine-globals --jest-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/no-label-var.md --- url: /docs/guide/usage/linter/rules/eslint/no-label-var.md --- ### What it does Disallow labels that share a name with a variable. ### Why is this bad? This rule aims to create clearer code by disallowing the bad practice of creating a label that shares a name with a variable that is in scope. ### Examples Examples of **incorrect** code for this rule: ```js var x = foo; function bar() { x: for (;;) { break x; } } ``` Examples of **correct** code for this rule: ```js // The variable that has the same name as the label is not in scope. function foo() { var q = t; } function bar() { q: for (;;) { break q; } } ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "no-label-var": "error" } } ``` ```bash [CLI] oxlint --deny no-label-var ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/no-labels.md --- url: /docs/guide/usage/linter/rules/eslint/no-labels.md --- ### What it does Disallow labeled statements. ### Why is this bad? Labeled statements in JavaScript are used in conjunction with `break` and `continue` to control flow around multiple loops. For example: ```js outer: while (true) { while (true) { break outer; } } ``` The `break outer` statement ensures that this code will not result in an infinite loop because control is returned to the next statement after the `outer` label was applied. If this statement was changed to be just `break`, control would flow back to the outer `while` statement and an infinite loop would result. While convenient in some cases, labels tend to be used only rarely and are frowned upon by some as a remedial form of flow control that is more error prone and harder to understand. ### Examples Examples of **incorrect** code for this rule: ```js label: while (true) { // ... } label: while (true) { break label; } label: while (true) { continue label; } label: switch (a) { case 0: break label; } label: { break label; } label: if (a) { break label; } ``` Examples of **correct** code for this rule: ```js var f = { label: "foo", }; while (true) { break; } while (true) { continue; } ``` ## Configuration This rule accepts a configuration object with the following properties: ### allowLoop type: `boolean` default: `false` If set to `true`, this rule ignores labels which are sticking to loop statements. Examples of **correct** code with this option set to `true`: ```js label: while (true) { break label; } ``` ### allowSwitch type: `boolean` default: `false` If set to `true`, this rule ignores labels which are sticking to switch statements. Examples of **correct** code with this option set to `true`: ```js label: switch (a) { case 0: break label; } ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "no-labels": "error" } } ``` ```bash [CLI] oxlint --deny no-labels ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/jest/no-large-snapshots.md --- url: /docs/guide/usage/linter/rules/jest/no-large-snapshots.md --- ### What it does Disallow large snapshots. ### Why is this bad? When using Jest's snapshot capability one should be mindful of the size of created snapshots. As a general best practice snapshots should be limited in size in order to be more manageable and reviewable. A stored snapshot is only as good as its review and as such keeping it short, sweet, and readable is important to allow for thorough reviews. ### Examples Examples of **incorrect** code for this rule: ```javascript exports[`a large snapshot 1`] = ` line 1 line 2 line 3 line 4 line 5 line 6 line 7 line 8 line 9 line 10 line 11 line 12 line 13 line 14 line 15 line 16 line 17 line 18 line 19 line 20 line 21 line 22 line 23 line 24 line 25 line 26 line 27 line 28 line 29 line 30 line 31 line 32 line 33 line 34 line 35 line 36 line 37 line 38 line 39 line 40 line 41 line 42 line 43 line 44 line 45 line 46 line 47 line 48 line 49 line 50 line 51 `; ``` Examples of **incorrect** code for this rule: ```js exports[`a more manageable and readable snapshot 1`] = ` line 1 line 2 line 3 line 4 `; ``` This rule is compatible with [eslint-plugin-vitest](https://github.com/vitest-dev/eslint-plugin-vitest/blob/main/docs/rules/no-large-snapshots.md), to use it, add the following configuration to your `.oxlintrc.json`: ```json { "rules": { "vitest/no-large-snapshots": "error" } } ``` ## Configuration This rule accepts a configuration object with the following properties: ### allowedSnapshots type: `Record` default: `{}` A map of snapshot file paths to arrays of snapshot names that are allowed to exceed the size limit. Snapshot names can be specified as regular expressions. ### inlineMaxSize type: `integer` default: `50` Maximum number of lines allowed for inline snapshots. ### maxSize type: `integer` default: `50` Maximum number of lines allowed for external snapshot files. ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["jest"], "rules": { "jest/no-large-snapshots": "error" } } ``` ```bash [CLI] oxlint --deny jest/no-large-snapshots --jest-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/unicorn/no-length-as-slice-end.md ## What it does Disallow using `length` as the end argument of a `slice` call. ## Why is this bad? Passing `length` as the end argument of a `slice` call is unnecessary and can be confusing. ## Examples Examples of **incorrect** code for this rule: ```javascript foo.slice(1, foo.length); ``` Examples of **correct** code for this rule: ```javascript foo.slice(1); ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "unicorn/no-length-as-slice-end": "error" } } ``` ```bash [CLI] oxlint --deny unicorn/no-length-as-slice-end ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/vue/no-lifecycle-after-await.md --- url: /docs/guide/usage/linter/rules/vue/no-lifecycle-after-await.md --- ### What it does Disallow asynchronously registered lifecycle hooks. ### Why is this bad? Lifecycle hooks must be registered synchronously during `setup()` execution. If a lifecycle hook is called after an `await` statement, it may be registered too late and might not work as expected. ### Examples Examples of **incorrect** code for this rule: ```vue ``` Examples of **correct** code for this rule: ```vue ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["vue"], "rules": { "vue/no-lifecycle-after-await": "error" } } ``` ```bash [CLI] oxlint --deny vue/no-lifecycle-after-await --vue-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/no-lone-blocks.md --- url: /docs/guide/usage/linter/rules/eslint/no-lone-blocks.md --- ### What it does Disallows unnecessary standalone block statements. ### Why is this bad? Standalone blocks can be confusing as they do not provide any meaningful purpose when used unnecessarily. They may introduce extra nesting, reducing code readability, and can mislead readers about scope or intent. ### Examples Examples of **incorrect** code for this rule: ```js { var x = 1; } ``` Examples of **correct** code for this rule: ```js if (condition) { var x = 1; } { let x = 1; // Used to create a valid block scope. } ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "no-lone-blocks": "error" } } ``` ```bash [CLI] oxlint --deny no-lone-blocks ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/unicorn/no-lonely-if.md ## Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/no-lonely-if.md ## What it does Disallow `if` statements as the only statement in `else` blocks ## Why is this bad? When an `if` statement is the only statement in an `else` block, it is often clearer to use an `else if` instead. ## Examples Examples of **incorrect** code for this rule: ```js if (condition) { // ... } else { if (anotherCondition) { // ... } } ``` ```js if (condition) { // ... } else { if (anotherCondition) { // ... } else { // ... } } ``` Examples of **correct** code for this rule: ```js if (condition) { // ... } else if (anotherCondition) { // ... } ``` ```js if (condition) { // ... } else if (anotherCondition) { // ... } else { // ... } ``` ```js if (condition) { // ... } else { if (anotherCondition) { // ... } doSomething(); } ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "no-lonely-if": "error" } } ``` ```bash [CLI] oxlint --deny no-lonely-if ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/no-loop-func.md --- url: /docs/guide/usage/linter/rules/eslint/no-loop-func.md --- ### What it does Disallows function declarations and expressions inside loop statements when they reference variables declared in the outer scope that may change across iterations. ### Why is this bad? Writing functions within loops tends to result in errors due to the way closures work in JavaScript. Functions capture variables by reference, not by value. When using `var`, which is function-scoped, all iterations share the same variable binding, leading to unexpected behavior. ### Examples Examples of **incorrect** code for this rule: ```js for (var i = 0; i < 10; i++) { funcs[i] = function () { return i; }; } ``` Examples of **correct** code for this rule: ```js for (let i = 0; i < 10; i++) { funcs[i] = function () { return i; }; } ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "no-loop-func": "error" } } ``` ```bash [CLI] oxlint --deny no-loop-func ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/no-loss-of-precision.md --- url: /docs/guide/usage/linter/rules/eslint/no-loss-of-precision.md --- ### What it does Disallow precision loss of number literal. ### Why is this bad? It can lead to unexpected results in certain situations. For example, when performing mathematical operations. In JavaScript, Numbers are stored as double-precision floating-point numbers according to the IEEE 754 standard. Because of this, numbers can only retain accuracy up to a certain amount of digits. If the programmer enters additional digits, those digits will be lost in the conversion to the Number type and will result in unexpected/incorrect behavior. ### Examples Examples of **incorrect** code for this rule: ```javascript var x = 2e999; ``` ```javascript var x = 9007199254740993; ``` ```javascript var x = 5123000000000000000000000000001; ``` ```javascript var x = 1230000000000000000000000.0; ``` ```javascript var x = 0x200000_0000000_1; ``` Examples of **correct** code for this rule: ```javascript var x = 12345; ``` ```javascript var x = 123.456; ``` ```javascript var x = 123.0; ``` ```javascript var x = 123e34; ``` ```javascript var x = 0x1fff_ffff_fff_fff; ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "no-loss-of-precision": "error" } } ``` ```bash [CLI] oxlint --deny no-loss-of-precision ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/unicorn/no-magic-array-flat-depth.md ## What it does Disallow magic numbers for `Array.prototype.flat` depth. ## Why is this bad? Magic numbers are hard to understand and maintain. When calling `Array.prototype.flat`, it is usually called with `1` or infinity. If you are using a different number, it is better to add a comment explaining the depth. ## Examples Examples of **incorrect** code for this rule: ```javascript array.flat(2); array.flat(20); ``` Examples of **correct** code for this rule: ```javascript array.flat(2 /* explanation */); array.flat(1); array.flat(); array.flat(Infinity); ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "unicorn/no-magic-array-flat-depth": "error" } } ``` ```bash [CLI] oxlint --deny unicorn/no-magic-array-flat-depth ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/no-magic-numbers.md --- url: /docs/guide/usage/linter/rules/eslint/no-magic-numbers.md --- ### What it does This rule aims to make code more readable and refactoring easier by ensuring that special numbers are declared as constants to make their meaning explicit. The current implementation does not support BigInt numbers inside array indexes. ### Why is this bad? ‘Magic numbers’ are numbers that occur multiple times in code without an explicit meaning. They should preferably be replaced by named constants. ### Examples Examples of **incorrect** code for this rule: ```javascript var dutyFreePrice = 100; var finalPrice = dutyFreePrice + dutyFreePrice * 0.25; ``` Examples of **correct** code for this rule with option "ignore": ```javascript /*typescript no-magic-numbers: ["error", { "ignore": [1] }]*/ var data = ["foo", "bar", "baz"]; var dataLast = data.length && data[data.length - 1]; ``` Examples of **correct** code for this rule with option "ignoreArrayIndexes": ```javascript /*typescript no-magic-numbers: ["error", { "ignoreArrayIndexes": true }]*/ var item = data[2]; data[100] = a; f(data[0]); a = data[-0]; // same as data[0], -0 will be coerced to "0" a = data[0xab]; a = data[5.6e1]; a = data[4294967294]; // max array index ``` Examples of **correct** code for this rule with option "ignoreDefaultValues": ```javascript /*typescript no-magic-numbers: ["error", { "ignoreDefaultValues": true }]*/ const { tax = 0.25 } = accountancy; function mapParallel(concurrency = 3) { /***/ } ``` Examples of **correct** code for this rule with option "ignoreClassFieldInitialValues": ```javascript /*typescript no-magic-numbers: ["error", { "ignoreClassFieldInitialValues": true }]*/ class C { foo = 2; bar = -3; #baz = 4; static qux = 5; } ``` Examples of **incorrect** code for this rule with option "enforceConst": ```javascript /*typescript no-magic-numbers: ["error", { "enforceConst": true }]*/ var TAX = 0.25; ``` Examples of **incorrect** code for this rule with option "detectObjects": ```javascript /*typescript no-magic-numbers: ["error", { "detectObjects": true }]*/ var magic = { tax: 0.25, }; ``` Examples of **correct** code for this rule with option "detectObjects": ```javascript /*typescript no-magic-numbers: ["error", { "detectObjects": true }]*/ var TAX = 0.25; var magic = { tax: TAX, }; ``` Examples of **correct** code for this rule with option "ignoreEnums": ```typescript /*typescript no-magic-numbers: ["error", { "ignoreEnums": true }]*/ enum foo { SECOND = 1000, } ``` Examples of **correct** code for this rule with option "ignoreNumericLiteralTypes": ```typescript /*typescript no-magic-numbers: ["error", { "ignoreNumericLiteralTypes": true }]*/ type SmallPrimes = 2 | 3 | 5 | 7 | 11; ``` Examples of **correct** code for this rule with option "ignoreReadonlyClassProperties": ```typescript /*typescript no-magic-numbers: ["error", { "ignoreReadonlyClassProperties": true }]*/ class Foo { readonly A = 1; readonly B = 2; public static readonly C = 1; static readonly D = 1; } ``` Examples of **correct** code for this rule with option "ignoreTypeIndexes": ```typescript /*typescript no-magic-numbers: ["error", { "ignoreTypeIndexes": true }]*/ type Foo = Bar[0]; type Baz = Parameters[2]; ``` ## Configuration This rule accepts a configuration object with the following properties: ### detectObjects type: `boolean` default: `false` When true, numeric literals used in object properties are considered magic numbers. ### enforceConst type: `boolean` default: `false` When true, enforces that number constants must be declared using `const` instead of `let` or `var`. ### ignore type: `array` default: `[]` An array of numbers to ignore if used as magic numbers. Can include floats or BigInt strings. #### ignore\[n] ### ignoreArrayIndexes type: `boolean` default: `false` When true, numeric literals used as array indexes are ignored. ### ignoreClassFieldInitialValues type: `boolean` default: `false` When true, numeric literals used as initial values in class fields are ignored. ### ignoreDefaultValues type: `boolean` default: `false` When true, numeric literals used as default values in function parameters and destructuring are ignored. ### ignoreEnums type: `boolean` default: `false` When true, numeric literals in TypeScript enums are ignored. ### ignoreNumericLiteralTypes type: `boolean` default: `false` When true, numeric literals used as TypeScript numeric literal types are ignored. ### ignoreReadonlyClassProperties type: `boolean` default: `false` When true, numeric literals in readonly class properties are ignored. ### ignoreTypeIndexes type: `boolean` default: `false` When true, numeric literals used to index TypeScript types are ignored. ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "no-magic-numbers": "error" } } ``` ```bash [CLI] oxlint --deny no-magic-numbers ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/oxc/no-map-spread.md --- url: /docs/guide/usage/linter/rules/oxc/no-map-spread.md --- ### What it does Disallow the use of object or array spreads in [`Array.prototype.map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) and [`Array.prototype.flatMap`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap) to add properties/elements to array items. This rule only seeks to report cases where the spread operator is used to merge objects or arrays, not where it is used to copy them. ### Why is this bad? Spreading is commonly used to add properties to objects in an array or to combine several objects together. Unfortunately, spreads incur a re-allocation for a new object, plus `O(n)` memory copies. ```ts // each object in scores gets shallow-copied. Since `scores` is never // reused, spreading is inefficient. function getDisplayData() { const scores: Array<{ username: string; score: number }> = getScores(); const displayData = scores.map((score) => ({ ...score, rank: getRank(score) })); return displayData; } ``` Unless you expect objects in the mapped array to be mutated later, it is better to use [`Object.assign`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign). ```ts // `score` is mutated in place and is more performant. function getDisplayData() { const scores: Array<{ username: string; score: number }> = getScores(); const displayData = scores.map((score) => Object.assign(score, { rank: getRank(score) })); return displayData; } ``` ### Protecting from Mutations There are valid use cases for spreading objects in `map` calls, specifically when you want consumers of returned arrays to be able to mutate them without affecting the original data. This rule makes a best-effort attempt to avoid reporting on these cases. Spreads on class instance properties are completely ignored: ```ts class AuthorsDb { #authors = []; public getAuthorsWithBooks() { return this.#authors.map((author) => ({ // protects against mutations, giving the callee their own // deep(ish) copy of the author object. ...author, books: getBooks(author), })); } } ``` Spreads on arrays that are re-read after the `map` call are also ignored by default. Configure this behavior with the `ignoreRereads` option. ``` /* "oxc/no-map-spread": ["error", { "ignoreRereads": true }] */ const scores = getScores(); const displayData = scores.map(score => ({ ...score, rank: getRank(score) })); console.log(scores); // scores is re-read after the map call ``` #### Arrays In the case of array spreads, [`Array.prototype.concat`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat) or [`Array.prototype.push`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push) should be used wherever possible. These have slignly different semantics than array spreads, since spreading works on iterables while `concat` and `push` work only on arrays. ```ts let arr = [1, 2, 3]; let set = new Set([4]); let a = [...arr, ...set]; // [1, 2, 3, 4] let b = arr.concat(set); // [1, 2, 3, Set(1)] // Alternative that is more performant than spreading but still has the // same semantics. Unfortunately, it is more verbose. let c = arr.concat(Array.from(set)); // [1, 2, 3, 4] // You could also use `Symbol.isConcatSpreadable` set[Symbol.isConcatSpreadable] = true; let d = arr.concat(set); // [1, 2, 3, 4] ``` ### Automatic Fixing This rule can automatically fix violations caused by object spreads, but does not fix arrays. Object spreads will get replaced with [`Object.assign`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign). Array fixing may be added in the future. Object expressions with a single element (the spread) are not fixed. ```js arr.map((x) => ({ ...x })); // not fixed ``` A `fix` is available (using `--fix`) for objects with "normal" elements before the spread. Since `Object.apply` mutates the first argument, and a new object will be created with those elements, the spread identifier will not be mutated. In effect, the spread semantics are preserved ```js // before arr.map(({ x, y }) => ({ x, ...y })); // after arr.map(({ x, y }) => Object.assign({ x }, y)); ``` A suggestion (using `--fix-suggestions`) is provided when a spread is the first property in an object. This fix mutates the spread identifier, meaning it could have unintended side effects. ```js // before arr.map(({ x, y }) => ({ ...x, y })); arr.map(({ x, y }) => ({ ...x, y })); // after arr.map(({ x, y }) => Object.assign(x, { y })); arr.map(({ x, y }) => Object.assign(x, y)); ``` ### Examples Examples of **incorrect** code for this rule: ```js const arr = [{ a: 1 }, { a: 2 }, { a: 3 }]; const arr2 = arr.map((obj) => ({ ...obj, b: obj.a * 2 })); ``` Examples of **correct** code for this rule: ```ts const arr = [{ a: 1 }, { a: 2 }, { a: 3 }]; arr.map((obj) => Object.assign(obj, { b: obj.a * 2 })); // instance properties are ignored class UsersDb { #users = []; public get users() { // clone users, providing caller with their own deep(ish) copy. return this.#users.map((user) => ({ ...user })); } } ``` ```tsx function UsersTable({ users }) { const usersWithRoles = users.map((user) => ({ ...user, role: getRole(user) })); return ( {usersWithRoles.map((user) => ( ))} {/* re-read of users */}
{user.name} {user.role}
Total users: {users.length}
); } ``` ### References * [ECMA262 - Object spread evaluation semantics](https://262.ecma-international.org/15.0/index.html#sec-runtime-semantics-propertydefinitionevaluation) * [JSPerf - `concat` vs array spread performance](https://jsperf.app/pihevu) ## Configuration This rule accepts a configuration object with the following properties: ### ignoreArgs type: `boolean` default: `true` Ignore maps on arrays passed as parameters to a function. This option is enabled by default to better avoid false positives. It comes at the cost of potentially missing spreads that are inefficient. We recommend turning this off in your `.oxlintrc.json` files. #### Examples Examples of **incorrect** code for this rule when `ignoreArgs` is `true`: ```ts /* "oxc/no-map-spread": ["error", { "ignoreArgs": true }] */ function foo(arr) { let arr2 = arr.filter((x) => x.a > 0); return arr2.map((x) => ({ ...x })); } ``` Examples of **correct** code for this rule when `ignoreArgs` is `true`: ```ts /* "oxc/no-map-spread": ["error", { "ignoreArgs": true }] */ function foo(arr) { return arr.map((x) => ({ ...x })); } ``` ### ignoreRereads type: `boolean` default: `true` Ignore mapped arrays that are re-read after the `map` call. Re-used arrays may rely on shallow copying behavior to avoid mutations. In these cases, `Object.assign` is not really more performant than spreads. ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "oxc/no-map-spread": "error" } } ``` ```bash [CLI] oxlint --deny oxc/no-map-spread ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/typescript/no-meaningless-void-operator.md ## What it does This rule disallows the void operator when its argument is already of type void or undefined. ## Why is this bad? The void operator is useful when you want to execute an expression and force it to evaluate to undefined. However, using void on expressions that are already of type void or undefined is meaningless and adds unnecessary complexity to the code. ## Examples Examples of **incorrect** code for this rule: ```ts function foo(): void { return; } void foo(); // meaningless, foo() already returns void void undefined; // meaningless, undefined is already undefined async function bar() { void (await somePromise); // meaningless if somePromise resolves to void } ``` Examples of **correct** code for this rule: ```ts function getValue(): number { return 42; } void getValue(); // meaningful, converts number to void void console.log("hello"); // meaningful, console.log returns undefined but we want to be explicit function processData() { // some processing } processData(); // no void needed since we don't care about return value ``` ## Configuration This rule accepts a configuration object with the following properties: ## checkNever type: `boolean` default: `false` Whether to check `void` applied to expressions of type `never`. ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "typescript/no-meaningless-void-operator": "error" } } ``` ```bash [CLI] oxlint --type-aware --deny typescript/no-meaningless-void-operator ``` ::: ## References * Rule Source * Rule Source (tsgolint) --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/no-misleading-character-class.md --- url: /docs/guide/usage/linter/rules/eslint/no-misleading-character-class.md --- ### What it does This rule reports regular expressions which include multiple code point characters in character class syntax. This includes: * Characters with combining marks (e.g., `Á` where `A` is followed by a combining acute accent) * Characters with emoji modifiers (e.g., `👶🏻`) * Pairs of regional indicator symbols (e.g., `🇯🇵`) * Characters joined by zero-width joiner (ZWJ) (e.g., `👨‍👩‍👦`) * Surrogate pairs without the Unicode flag (e.g., `/^[👍]$/`) ### Why is this bad? Unicode includes characters which are made by multiple code points. RegExp character class syntax (`/[abc]/`) cannot handle characters which are made by multiple code points as a character; those characters will be dissolved to each code point. For example, `❇️` is made by `❇` (`U+2747`) and VARIATION SELECTOR-16 (`U+FE0F`). If this character is in a RegExp character class, it will match either `❇` (`U+2747`) or VARIATION SELECTOR-16 (`U+FE0F`) rather than `❇️`. This can lead to regular expressions that do not match what the author intended, especially for emoji, regional indicators, and characters with combining marks. #### Examples Examples of **incorrect** code for this rule: ```javascript /^[Á]$/u; /^[❇️]$/u; /^[👶🏻]$/u; /^[🇯🇵]$/u; /^[👨‍👩‍👦]$/u; /^[👍]$/; new RegExp("[🎵]"); ``` Examples of **correct** code for this rule: ```javascript /^[abc]$/; /^[👍]$/u; /[\u00B7\u0300-\u036F]/u; new RegExp("^[\u{1F1EF}\u{1F1F5}]", "u"); ``` ## Configuration This rule accepts a configuration object with the following properties: ### allowEscape type: `boolean` default: `false` When set to `true`, the rule allows any grouping of code points inside a character class as long as they are written using escape sequences. Examples of **incorrect** code for this rule with `{ "allowEscape": true }`: ```javascript /[\uD83D]/; // backslash can be omitted new RegExp("[\ud83d" + "\udc4d]"); ``` Examples of **correct** code for this rule with `{ "allowEscape": true }`: ```javascript /[\ud83d\udc4d]/; /[\u00B7\u0300-\u036F]/u; /[👨\u200d👩]/u; new RegExp("[\x41\u0301]"); new RegExp(`[\u{1F1EF}\u{1F1F5}]`, "u"); new RegExp("[\\u{1F1EF}\\u{1F1F5}]", "u"); ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "no-misleading-character-class": "error" } } ``` ```bash [CLI] oxlint --deny no-misleading-character-class ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/typescript/no-misused-new.md ## What it does Enforces valid definition of new and constructor. This rule prevents classes from defining a method named `new` and interfaces from defining a method named `constructor`. ## Why is this bad? JavaScript classes may define a constructor method that runs when a class instance is newly created. TypeScript allows interfaces that describe a static class object to define a `new()` method (though this is rarely used in real world code). Developers new to JavaScript classes and/or TypeScript interfaces may sometimes confuse when to use constructor or new. ## Examples Examples of **incorrect** code for this rule: ```typescript declare class C { new(): C; } ``` ```typescript interface I { new (): I; constructor(): void; } ``` Examples of **correct** code for this rule: ```typescript declare class C { constructor(); } ``` ```typescript interface I { new (): C; } ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "typescript/no-misused-new": "error" } } ``` ```bash [CLI] oxlint --deny typescript/no-misused-new ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/typescript/no-misused-promises.md ## What it does This rule forbids providing Promises to logical locations such as if statements in places where the TypeScript compiler allows them but they are not handled properly. These situations can often arise due to a missing `await` keyword or just a misunderstanding of the way async functions are handled/awaited. ## Why is this bad? Misused promises can cause crashes or other unexpected behavior, unless there are possibly some global unhandled promise handlers registered. ## Examples Examples of **incorrect** code for this rule: ```ts // Promises in conditionals: const promise = Promise.resolve("value"); if (promise) { // Do something } // Promises where `void` return was expected: [1, 2, 3].forEach(async (value) => { await fetch(`/${value}`); }); // Spreading Promises: const getData = () => fetch("/"); console.log({ foo: 42, ...getData() }); ``` Examples of **correct** code for this rule: ```ts // Awaiting the Promise to get its value in a conditional: const promise = Promise.resolve("value"); if (await promise) { // Do something } // Using a `for-of` with `await` inside (instead of `forEach`): for (const value of [1, 2, 3]) { await fetch(`/${value}`); } // Spreading data returned from Promise, instead of the Promise itself: const getData = () => fetch("/"); console.log({ foo: 42, ...(await getData()) }); ``` ## Configuration This rule accepts a configuration object with the following properties: ## checksConditionals type: `boolean` default: `true` Whether to check if Promises are used in conditionals. When true, disallows using Promises in conditions where a boolean is expected. ## checksSpreads type: `boolean` default: `true` Whether to check if Promises are used in spread syntax. When true, disallows spreading Promise values. ## checksVoidReturn type: `object | boolean` ### checksVoidReturn.arguments type: `boolean` default: `true` Whether to check Promise-returning functions passed as arguments to void-returning functions. ### checksVoidReturn.attributes type: `boolean` default: `true` Whether to check Promise-returning functions in JSX attributes expecting void. ### checksVoidReturn.inheritedMethods type: `boolean` default: `true` Whether to check Promise-returning methods that override void-returning inherited methods. ### checksVoidReturn.properties type: `boolean` default: `true` Whether to check Promise-returning functions assigned to object properties expecting void. ### checksVoidReturn.returns type: `boolean` default: `true` Whether to check Promise values returned from void-returning functions. ### checksVoidReturn.variables type: `boolean` default: `true` Whether to check Promise-returning functions assigned to variables typed as void-returning. ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "typescript/no-misused-promises": "error" } } ``` ```bash [CLI] oxlint --type-aware --deny typescript/no-misused-promises ``` ::: ## References * Rule Source * Rule Source (tsgolint) --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/typescript/no-misused-spread.md ## What it does This rule disallows spreading syntax in places where it doesn't make sense or could cause runtime errors. ## Why is this bad? The spread operator can be misused in ways that might not be immediately obvious but can cause runtime errors or unexpected behavior. This rule helps catch common misuses. ## Examples Examples of **incorrect** code for this rule: ```ts // Spreading a non-iterable value in an array const num = 42; const arr = [...num]; // Runtime error: num is not iterable // Spreading a Promise in an array const promise = Promise.resolve([1, 2, 3]); const arr2 = [...promise]; // Runtime error: Promise is not iterable // Spreading non-object in object literal const str = "hello"; const obj = { ...str }; // Creates { '0': 'h', '1': 'e', ... } which might be unexpected ``` Examples of **correct** code for this rule: ```ts // Spreading arrays const arr1 = [1, 2, 3]; const arr2 = [...arr1]; // Spreading objects const obj1 = { a: 1, b: 2 }; const obj2 = { ...obj1 }; // Spreading resolved Promise const promise = Promise.resolve([1, 2, 3]); const arr3 = [...(await promise)]; // Using Array.from for non-iterables if needed const str = "hello"; const arr4 = Array.from(str); // ['h', 'e', 'l', 'l', 'o'] ``` ## Configuration This rule accepts a configuration object with the following properties: ## allow type: `array` default: `[]` An array of type or value specifiers that are allowed to be spread even if they would normally be flagged as misused. ### allow\[n] type: `string` Type or value specifier for matching specific declarations Supports four types of specifiers: 1. **String specifier** (deprecated): Universal match by name ```json "Promise" ``` 1. **File specifier**: Match types/values declared in local files ```json { "from": "file", "name": "MyType" } { "from": "file", "name": ["Type1", "Type2"] } { "from": "file", "name": "MyType", "path": "./types.ts" } ``` 1. **Lib specifier**: Match TypeScript built-in lib types ```json { "from": "lib", "name": "Promise" } { "from": "lib", "name": ["Promise", "PromiseLike"] } ``` 1. **Package specifier**: Match types/values from npm packages ```json { "from": "package", "name": "Observable", "package": "rxjs" } { "from": "package", "name": ["Observable", "Subject"], "package": "rxjs" } ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "typescript/no-misused-spread": "error" } } ``` ```bash [CLI] oxlint --type-aware --deny typescript/no-misused-spread ``` ::: ## References * Rule Source * Rule Source (tsgolint) --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/typescript/no-mixed-enums.md ## What it does This rule disallows enums from having both string and numeric members. ## Why is this bad? TypeScript enums can have string, numeric, or computed members. Having mixed string and numeric members in the same enum can lead to confusion and unexpected runtime behavior due to how TypeScript compiles enums. ## Examples Examples of **incorrect** code for this rule: ```ts enum Status { Open = 1, Closed = "closed", } enum Direction { Up = "up", Down = 2, Left = "left", Right = 4, } ``` Examples of **correct** code for this rule: ```ts // All numeric enum Status { Open = 1, Closed = 2, } // All string enum Direction { Up = "up", Down = "down", Left = "left", Right = "right", } // Auto-incremented numeric enum Color { Red, Green, Blue, } ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "typescript/no-mixed-enums": "error" } } ``` ```bash [CLI] oxlint --type-aware --deny typescript/no-mixed-enums ``` ::: ## References * Rule Source * Rule Source (tsgolint) --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/jest/no-mocks-import.md --- url: /docs/guide/usage/linter/rules/jest/no-mocks-import.md --- ### What it does This rule reports imports from a path containing a **mocks** component. ### Why is this bad? Manually importing mocks from a `__mocks__` directory can lead to unexpected behavior and breaks Jest's automatic mocking system. Jest is designed to automatically resolve and use mocks from `__mocks__` directories when `jest.mock()` is called. Directly importing from these directories bypasses Jest's module resolution system and can cause inconsistencies between test and production environments. ### Examples Examples of **incorrect** code for this rule: ```ts import thing from "./__mocks__/index"; require("./__mocks__/index"); ``` Examples of **correct** code for this rule: ```ts import thing from "thing"; require("thing"); ``` This rule is compatible with [eslint-plugin-vitest](https://github.com/vitest-dev/eslint-plugin-vitest/blob/main/docs/rules/no-mocks-import.md), to use it, add the following configuration to your `.oxlintrc.json`: ```json { "rules": { "vitest/no-mocks-import": "error" } } ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["jest"], "rules": { "jest/no-mocks-import": "error" } } ``` ```bash [CLI] oxlint --deny jest/no-mocks-import --jest-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/no-multi-assign.md --- url: /docs/guide/usage/linter/rules/eslint/no-multi-assign.md --- ### What it does Disallow use of chained assignment expressions. ### Why is this bad? Chaining the assignment of variables can lead to unexpected results and be difficult to read. ```js (function () { const foo = (bar = 0); // Did you mean `foo = bar == 0`? bar = 1; // This will not fail since `bar` is not constant. })(); console.log(bar); // This will output 1 since `bar` is not scoped. ``` ### Examples Examples of **incorrect** code for this rule: ```js var a = (b = c = 5); const foo = (bar = "baz"); let d = (e = f); class Foo { a = (b = 10); } a = b = "quux"; ``` Examples of **correct** code for this rule: ```js var a = 5; var b = 5; var c = 5; const foo = "baz"; const bar = "baz"; let d = c; let e = c; class Foo { a = 10; b = 10; } a = "quux"; b = "quux"; ``` ## Configuration This rule accepts a configuration object with the following properties: ### ignoreNonDeclaration type: `boolean` default: `false` When set to `true`, the rule allows chains that don't include initializing a variable in a declaration or initializing a class field. Examples of **correct** code for this option set to `true`: ```js let a; let b; a = b = "baz"; const x = {}; const y = {}; x.one = y.one = 1; ``` Examples of **incorrect** code for this option set to `true`: ```js let a = (b = "baz"); const foo = (bar = 1); class Foo { a = (b = 10); } ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "no-multi-assign": "error" } } ``` ```bash [CLI] oxlint --deny no-multi-assign ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/react/no-multi-comp.md --- url: /docs/guide/usage/linter/rules/react/no-multi-comp.md --- ### What it does Prevents multiple React components from being defined in the same file. ### Why is this bad? Declaring multiple components in a single file can make it harder to navigate and maintain the codebase. Each component should ideally be in its own file for better organization and reusability. ### Examples Examples of **incorrect** code for this rule: ```jsx function Foo({ name }) { return
Hello {name}
; } function Bar({ name }) { return
Hello again {name}
; } ``` Examples of **correct** code for this rule: ```jsx function Foo({ name }) { return
Hello {name}
; } ``` ## Configuration ### ignoreStateless type: `boolean` default: `false` When `true`, the rule will ignore stateless components and will allow you to have multiple stateless components in the same file. Or one stateful component and one-or-more stateless components in the same file. Stateless basically just means function components, including those created via `memo` and `forwardRef`. ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["react"], "rules": { "react/no-multi-comp": "error" } } ``` ```bash [CLI] oxlint --deny react/no-multi-comp --react-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/no-multi-str.md --- url: /docs/guide/usage/linter/rules/eslint/no-multi-str.md --- ### What it does Disallow multiline strings. ### Why is this bad? Some consider this to be a bad practice as it was an undocumented feature of JavaScript that was only formalized later. ### Examples Examples of **incorrect** code for this rule: ```javascript var x = "Line 1 \ Line 2"; ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "no-multi-str": "error" } } ``` ```bash [CLI] oxlint --deny no-multi-str ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/promise/no-multiple-resolved.md --- url: /docs/guide/usage/linter/rules/promise/no-multiple-resolved.md --- ### What it does This rule warns of paths that resolve multiple times in executor functions that Promise constructors. ### Why is this bad? Multiple resolve/reject calls: * Violate the Promise/A+ specification * Have no effect on the Promise's behavior * Make the code's intent unclear * May indicate logical errors in the implementation ### Examples Examples of **incorrect** code for this rule: ```javascript new Promise((resolve, reject) => { fn((error, value) => { if (error) { reject(error); } resolve(value); // Both `reject` and `resolve` may be called. }); }); ``` Examples of **correct** code for this rule: ```javascript new Promise((resolve, reject) => { fn((error, value) => { if (error) { reject(error); } else { resolve(value); } }); }); ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["promise"], "rules": { "promise/no-multiple-resolved": "error" } } ``` ```bash [CLI] oxlint --deny promise/no-multiple-resolved --promise-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/vue/no-multiple-slot-args.md --- url: /docs/guide/usage/linter/rules/vue/no-multiple-slot-args.md --- ### What it does Disallow passing multiple arguments to scoped slots. ### Why is this bad? Users have to use the arguments in fixed order and cannot omit the ones they don't need. e.g. if you have a slot that passes in 5 arguments but the user actually only need the last 2 of them, they will have to declare all 5 just to use the last 2. More information can be found in [vuejs/vue#9468](https://github.com/vuejs/vue/issues/9468#issuecomment-462210146) ### Examples Examples of **incorrect** code for this rule: ```vue ``` Examples of **correct** code for this rule: ```vue ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["vue"], "rules": { "vue/no-multiple-slot-args": "error" } } ``` ```bash [CLI] oxlint --deny vue/no-multiple-slot-args --vue-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/import/no-mutable-exports.md --- url: /docs/guide/usage/linter/rules/import/no-mutable-exports.md --- ### What it does Forbids the use of mutable exports with var or let. ### Why is this bad? In general, we should always export constants ### Examples Examples of **incorrect** code for this rule: ```js export let count = 2; export var count = 3; let count = 4; export { count }; ``` Examples of **correct** code for this rule: ```js export const count = 1; export function getCount() {} export class Counter {} ``` ### Functions/Classes Note that exported function/class declaration identifiers may be reassigned, but are not flagged by this rule at this time. They may be in the future. ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["import"], "rules": { "import/no-mutable-exports": "error" } } ``` ```bash [CLI] oxlint --deny import/no-mutable-exports --import-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/import/no-named-as-default-member.md --- url: /docs/guide/usage/linter/rules/import/no-named-as-default-member.md --- ### What it does Reports the use of an exported name (named export) as a property on the default export. This occurs when trying to access a named export through the default export, which is incorrect. ### Why is this bad? Accessing a named export via the default export is incorrect and will not work as expected. Named exports should be imported directly, while default exports are accessed without properties. This mistake can lead to runtime errors or undefined behavior. ### Examples Given ```javascript // ./bar.js export function bar() { return null; } export default () => { return 1; }; ``` Examples of **incorrect** code for this rule: ```javascript // ./foo.js import foo from "./bar"; const bar = foo.bar; // Incorrect: trying to access named export via default ``` Examples of **correct** code for this rule: ```javascript // ./foo.js import { bar } from "./bar"; // Correct: accessing named export directly ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["import"], "rules": { "import/no-named-as-default-member": "error" } } ``` ```bash [CLI] oxlint --deny import/no-named-as-default-member --import-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/import/no-named-as-default.md --- url: /docs/guide/usage/linter/rules/import/no-named-as-default.md --- ### What it does Reports use of an exported name as the locally imported name of a default export. This happens when an imported default export is assigned a name that conflicts with a named export from the same module. ### Why is this bad? Using a named export's identifier for a default export can cause confusion and errors in understanding which value is being imported. It also reduces code clarity, making it harder for other developers to understand the intended imports. ### Examples Given ```javascript // foo.js export default "foo"; export const bar = "baz"; ``` Examples of **incorrect** code for this rule: ```javascript // Invalid: using exported name 'bar' as the identifier for default export. import bar from "./foo.js"; ``` Examples of **correct** code for this rule: ```javascript // Valid: correctly importing default export with a non-conflicting name. import foo from "./foo.js"; ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["import"], "rules": { "import/no-named-as-default": "error" } } ``` ```bash [CLI] oxlint --deny import/no-named-as-default --import-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/import/no-named-default.md --- url: /docs/guide/usage/linter/rules/import/no-named-default.md --- ### What it does Reports use of a default export as a locally named import. ### Why is this bad? Rationale: the syntax exists to import default exports expressively, let's use it. ### Examples Examples of **incorrect** code for this rule: ```js // message: Using exported name 'bar' as identifier for default export. import { default as foo } from "./foo.js"; import { default as foo, bar } from "./foo.js"; ``` Examples of **correct** code for this rule: ```js import foo from "./foo.js"; import foo, { bar } from "./foo.js"; ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["import"], "rules": { "import/no-named-default": "error" } } ``` ```bash [CLI] oxlint --deny import/no-named-default --import-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/import/no-named-export.md --- url: /docs/guide/usage/linter/rules/import/no-named-export.md --- ### What it does Prohibit named exports. ### Why is this bad? Named exports require strict identifier matching and can lead to fragile imports, while default exports enforce a single, consistent module entry point. ### Examples Examples of **incorrect** code for this rule: ```js export const foo = "foo"; const bar = "bar"; export { bar }; ``` Examples of **correct** code for this rule: ```js export default 'bar'; const foo = 'foo'; export { foo as default } ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["import"], "rules": { "import/no-named-export": "error" } } ``` ```bash [CLI] oxlint --deny import/no-named-export --import-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/typescript/no-namespace.md ## Source: https://oxc.rs/docs/guide/usage/linter/rules/react/no-namespace.md ## Source: https://oxc.rs/docs/guide/usage/linter/rules/import/no-namespace.md ## What it does Enforce a convention of not using namespaced (a.k.a. "wildcard" \*) imports. ## Why is this bad? Namespaced imports, while sometimes used, are generally considered less ideal in modern JavaScript development for several reasons: 1. **Specificity and Namespace Pollution**: * **Specificity**: Namespaced imports import the entire module, bringing in everything, even if you only need a few specific functions or classes. This can lead to potential naming conflicts if different modules have the same names for different functions. * **Pollution**: Importing an entire namespace pollutes your current scope with potentially unnecessary functions and variables. It increases the chance of accidental use of an unintended function or variable, leading to harder-to-debug errors. 1. **Maintainability**: * **Clarity**: Namespaced imports can make it harder to understand which specific functions or classes are being used in your code. This is especially true in larger projects with numerous imports. * **Refactoring**: If a function or class name changes within the imported module, you might need to update several parts of your code if you are using namespaced imports. This becomes even more challenging when dealing with multiple namespaces. 1. **Modern Practice**: * **Explicit Imports**: Modern JavaScript practices encourage explicit imports for specific components. This enhances code readability and maintainability. * **Tree-Shaking**: Tools like Webpack and Rollup use tree-shaking to remove unused code from your bundles. Namespaced imports can prevent efficient tree-shaking, leading to larger bundle sizes. ## Examples Examples of **incorrect** code for this rule: ```js import * as user from "user-lib"; import some, * as user from "./user"; ``` Examples of **correct** code for this rule: ```js import { getUserName, isUser } from "user-lib"; import user from "user-lib"; import defaultExport, { isUser } from "./user"; ``` ## Configuration This rule accepts a configuration object with the following properties: ## ignore type: `string[]` default: `[]` An array of glob strings for modules that should be ignored by the rule. For example, `["*.json"]` will ignore all JSON imports. ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["import"], "rules": { "import/no-namespace": "error" } } ``` ```bash [CLI] oxlint --deny import/no-namespace --import-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/no-negated-condition.md --- url: /docs/guide/usage/linter/rules/eslint/no-negated-condition.md --- ### What it does Disallow negated conditions. ### Why is this bad? Negated conditions are more difficult to understand. Code can be made more readable by inverting the condition. ### Examples Examples of **incorrect** code for this rule: ```javascript if (!a) { doSomethingC(); } else { doSomethingB(); } !a ? doSomethingC() : doSomethingB(); ``` Examples of **correct** code for this rule: ```javascript if (a) { doSomethingB(); } else { doSomethingC(); } a ? doSomethingB() : doSomethingC(); ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "no-negated-condition": "error" } } ``` ```bash [CLI] oxlint --deny no-negated-condition ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/unicorn/no-negation-in-equality-check.md ## What it does Disallow negated expressions on the left of (in)equality checks. ## Why is this bad? A negated expression on the left of an (in)equality check is likely a mistake from trying to negate the whole condition. ## Examples Examples of **incorrect** code for this rule: ```javascript if (!foo === bar) { } if (!foo !== bar) { } ``` Examples of **correct** code for this rule: ```javascript if (foo !== bar) { } if (!(foo === bar)) { } ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "unicorn/no-negation-in-equality-check": "error" } } ``` ```bash [CLI] oxlint --deny unicorn/no-negation-in-equality-check ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/unicorn/no-nested-ternary.md ## Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/no-nested-ternary.md ## What it does Disallows nested ternary expressions to improve code readability and maintainability. ## Why is this bad? Nested ternary expressions make code harder to read and understand. They can lead to complex, difficult-to-debug logic. ## Examples Examples of **incorrect** code for this rule: ```js const result = condition1 ? (condition2 ? "a" : "b") : "c"; ``` Examples of **correct** code for this rule: ```js let result; if (condition1) { result = condition2 ? "a" : "b"; } else { result = "c"; } ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "no-nested-ternary": "error" } } ``` ```bash [CLI] oxlint --deny no-nested-ternary ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/promise/no-nesting.md --- url: /docs/guide/usage/linter/rules/promise/no-nesting.md --- ### What it does Disallow nested then() or catch() statements. ### Why is this bad? Nesting promises makes code harder to read and understand. ### Examples Examples of **incorrect** code for this rule: ```javascript doThing().then(() => a.then()); doThing().then(function () { a.then(); }); doThing().then(() => { b.catch(); }); doThing().catch((val) => doSomething(val).catch(errors)); ``` Examples of **correct** code for this rule: ```javascript doThing().then(() => 4); doThing().then(function () { return 4; }); doThing().catch(() => 4); ``` ```javascript doThing() .then(() => Promise.resolve(1)) .then(() => Promise.resolve(2)); ``` This example is not a rule violation as unnesting here would result in `a` being undefined in the expression `getC(a, b)`. ```javascript doThing().then((a) => getB(a).then((b) => getC(a, b))); ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["promise"], "rules": { "promise/no-nesting": "error" } } ``` ```bash [CLI] oxlint --deny promise/no-nesting --promise-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/unicorn/no-new-array.md ## What it does Disallow `new Array()`. ## Why is this bad? When using the `Array` constructor with one argument, it's not clear whether the argument is meant to be the length of the array or the only element. ## Examples Examples of **incorrect** code for this rule: ```javascript const array = new Array(1); const array = new Array(42); const array = new Array(foo); ``` Examples of **correct** code for this rule: ```javascript const array = Array.from({ length: 42 }); const array = [42]; ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "unicorn/no-new-array": "error" } } ``` ```bash [CLI] oxlint --deny unicorn/no-new-array ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/unicorn/no-new-buffer.md ## What it does Disallows the deprecated `new Buffer()` constructor. ## Why is this bad? Enforces the use of [Buffer.from](https://nodejs.org/api/buffer.html#static-method-bufferfromarray) and [Buffer.alloc()](https://nodejs.org/api/buffer.html#static-method-bufferallocsize-fill-encoding) instead of [new Buffer()](https://nodejs.org/api/buffer.html#new-bufferarray), which has been deprecated since Node.js 4. ## Examples Examples of **incorrect** code for this rule: ```javascript const buffer = new Buffer(10); ``` Examples of **correct** code for this rule: ```javascript const buffer = Buffer.alloc(10); ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "unicorn/no-new-buffer": "error" } } ``` ```bash [CLI] oxlint --deny unicorn/no-new-buffer ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/no-new-func.md --- url: /docs/guide/usage/linter/rules/eslint/no-new-func.md --- ### What it does The rule disallow `new` operators with the `Function` object. ### Why is this bad? Using `new Function` or `Function` can lead to code that is difficult to understand and maintain. It can introduce security risks similar to those associated with `eval` because it generates a new function from a string of code, which can be a vector for injection attacks. Additionally, it impacts performance negatively as these functions are not optimized by the JavaScript engine. ### Examples Examples of **incorrect** code for this rule: ```js var x = new Function("a", "b", "return a + b"); var x = Function("a", "b", "return a + b"); var x = Function.call(null, "a", "b", "return a + b"); var x = Function.apply(null, ["a", "b", "return a + b"]); var x = Function.bind(null, "a", "b", "return a + b")(); var f = Function.bind(null, "a", "b", "return a + b"); ``` Examples of **correct** code for this rule: ```js let x = function (a, b) { return a + b; }; ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "no-new-func": "error" } } ``` ```bash [CLI] oxlint --deny no-new-func ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/no-new-native-nonconstructor.md --- url: /docs/guide/usage/linter/rules/eslint/no-new-native-nonconstructor.md --- ### What it does Disallow `new` operators with global non-constructor functions (`Symbol`, `BigInt`). This rule can be disabled for TypeScript code, as the TypeScript compiler enforces this check. ### Why is this bad? Both `new Symbol` and `new BigInt` throw a type error because they are functions and not classes. It is easy to make this mistake by assuming the uppercase letters indicate classes. ### Examples Examples of **incorrect** code for this rule: ```js // throws a TypeError let foo = new Symbol("foo"); // throws a TypeError let result = new BigInt(9007199254740991); ``` Examples of **correct** code for this rule: ```js let foo = Symbol("foo"); let result = BigInt(9007199254740991); ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "no-new-native-nonconstructor": "error" } } ``` ```bash [CLI] oxlint --deny no-new-native-nonconstructor ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/node/no-new-require.md --- url: /docs/guide/usage/linter/rules/node/no-new-require.md --- ### What it does Warn about calling `new` on `require`. ### Why is this bad? The `require` function is used to include modules and might return a constructor. As this is not always the case this can be confusing. ### Examples Examples of **incorrect** code for this rule: ```js var appHeader = new require("app-header"); ``` Examples of **correct** code for this rule: ```js var AppHeader = require("app-header"); var appHeader = new AppHeader(); ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["node"], "rules": { "node/no-new-require": "error" } } ``` ```bash [CLI] oxlint --deny node/no-new-require --node-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/promise/no-new-statics.md --- url: /docs/guide/usage/linter/rules/promise/no-new-statics.md --- ### What it does Disallows calling new on static `Promise` methods. ### Why is this bad? Calling a static `Promise` method with `new` is invalid and will result in a `TypeError` at runtime. ### Examples Examples of **incorrect** code for this rule: ```javascript const x = new Promise.resolve(value); ``` Examples of **correct** code for this rule: ```javascript const x = Promise.resolve(value); ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["promise"], "rules": { "promise/no-new-statics": "error" } } ``` ```bash [CLI] oxlint --deny promise/no-new-statics --promise-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/no-new-wrappers.md --- url: /docs/guide/usage/linter/rules/eslint/no-new-wrappers.md --- ### What it does Disallow `new` operators with the `String`, `Number`, and `Boolean` objects ### Why is this bad? The first problem is that primitive wrapper objects are, in fact, objects. That means typeof will return `"object"` instead of `"string"`, `"number"`, or `"boolean"`. The second problem comes with boolean objects. Every object is truthy, that means an instance of `Boolean` always resolves to `true` even when its actual value is `false`. https://eslint.org/docs/latest/rules/no-new-wrappers ### Examples Examples of **incorrect** code for this rule: ```js var stringObject = new String("Hello world"); var numberObject = new Number(33); var booleanObject = new Boolean(false); var symbolObject = new Symbol("foo"); // symbol is not a constructor ``` Examples of **correct** code for this rule: ```js var stringObject = "Hello world"; var stringObject2 = String(value); var numberObject = Number(value); var booleanObject = Boolean(value); var symbolObject = Symbol("foo"); ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "no-new-wrappers": "error" } } ``` ```bash [CLI] oxlint --deny no-new-wrappers ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/no-new.md --- url: /docs/guide/usage/linter/rules/eslint/no-new.md --- ### What it does Disallow new operators outside of assignments or comparisons. ### Why is this bad? Calling new without assigning or comparing it the reference is thrown away and in many cases the constructor can be replaced with a function. ### Examples Examples of **incorrect** code for this rule: ```javascript new Person(); () => { new Date(); }; ``` Examples of **correct** code for this rule: ```javascript var a = new Date()(() => new Date()); ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "no-new": "error" } } ``` ```bash [CLI] oxlint --deny no-new ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/import/no-nodejs-modules.md --- url: /docs/guide/usage/linter/rules/import/no-nodejs-modules.md --- ### What it does Forbid the use of Node.js builtin modules. Can be useful for client-side web projects that do not have access to those modules. ### Why is this bad? Node.js builtins (e.g. `fs`, `path`, `crypto`) are not available in browsers, so importing them in client bundles causes runtime failures or forces bundlers to inject heavy polyfills/shims. This increases bundle size, can leak server-only logic to the client, and may hide environment mismatches until production. ### Examples Examples of **incorrect** code for this rule: ```js import fs from "fs"; import path from "path"; var fs = require("fs"); var path = require("path"); ``` Examples of **correct** code for this rule: ```js import _ from "lodash"; import foo from "foo"; import foo from "./foo"; var _ = require("lodash"); var foo = require("foo"); var foo = require("./foo"); /* eslint import/no-nodejs-modules: ["error", {"allow": ["path"]}] */ import path from "path"; ``` ## Configuration This rule accepts a configuration object with the following properties: ### allow type: `string[]` Array of names of allowed modules. Defaults to an empty array. ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "plugins": ["import"], "rules": { "import/no-nodejs-modules": "error" } } ``` ```bash [CLI] oxlint --deny import/no-nodejs-modules --import-plugin ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/typescript/no-non-null-asserted-nullish-coalescing.md ## What it does Disallow non-null assertions in the left operand of a nullish coalescing operator. ## Why is this bad? The ?? nullish coalescing runtime operator allows providing a default value when dealing with null or undefined. Using a ! non-null assertion type operator in the left operand of a nullish coalescing operator is redundant, and likely a sign of programmer error or confusion over the two operators. ## Examples Examples of **incorrect** code for this rule: ```ts foo! ?? bar; foo.bazz! ?? bar; foo!.bazz! ?? bar; foo()! ?? bar; let x!: string; x! ?? ""; let x: string; x = foo(); x! ?? ""; ``` Examples of **correct** code for this rule: ```ts foo ?? bar; foo ?? bar!; foo!.bazz ?? bar; foo!.bazz ?? bar!; foo() ?? bar; ``` ```ts // This is considered correct code because there's no way for the user to satisfy it. let x: string; x! ?? ""; ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "typescript/no-non-null-asserted-nullish-coalescing": "error" } } ``` ```bash [CLI] oxlint --deny typescript/no-non-null-asserted-nullish-coalescing ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/typescript/no-non-null-asserted-optional-chain.md ## What it does Disallow non-null assertions after an optional chain expression. ## Why is this bad? By design, optional chain expressions (`?.`) provide `undefined` as the expression's value, if the object being accessed is `null` or `undefined`, instead of throwing an error. Using a non-null assertion (`!`) to assert the result of an optional chain expression is contradictory and likely wrong, as it indicates the code is both expecting the value to be potentially `null` or `undefined` and non-null at the same time. In most cases, either: 1. The object is not nullable and did not need the `?.` for its property lookup 1. The non-null assertion is incorrect and introduces a type safety hole. ## Examples Examples of **incorrect** code for this rule: ```ts foo?.bar!; foo?.bar()!; ``` Examples of **correct** code for this rule: ```ts foo?.bar; foo.bar!; ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "typescript/no-non-null-asserted-optional-chain": "error" } } ``` ```bash [CLI] oxlint --deny typescript/no-non-null-asserted-optional-chain ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/typescript/no-non-null-assertion.md ## What it does Disallow non-null assertions using the ! postfix operator. ## Why is this bad? TypeScript's ! non-null assertion operator asserts to the type system that an expression is non-nullable, as in not null or undefined. Using assertions to tell the type system new information is often a sign that code is not fully type-safe. It's generally better to structure program logic so that TypeScript understands when values may be nullable. ## Examples Examples of **incorrect** code for this rule: ```ts x!; x!.y; x.y!; ``` Examples of **correct** code for this rule: ```ts x; x?.y; x.y; ``` ## How to use To **enable** this rule using the config file or in the CLI, you can use: ::: code-group ```json [Config (.oxlintrc.json)] { "rules": { "typescript/no-non-null-assertion": "error" } } ``` ```bash [CLI] oxlint --deny typescript/no-non-null-assertion ``` ::: ## References * Rule Source --- # Source: https://oxc.rs/docs/guide/usage/linter/rules/jsx_a11y/no-noninteractive-tabindex.md --- url: /docs/guide/usage/linter/rules/jsx_a11y/no-noninteractive-tabindex.md --- ### What it does This rule checks that non-interactive elements don't have a tabIndex which would make them interactive via keyboard navigation. ### Why is this bad? Tab key navigation should be limited to elements on the page that can be interacted with. Thus it is not necessary to add a tabindex to items in an unordered list, for example, to make them navigable through assistive technology. These applications already afford page traversal mechanisms based on the HTML of the page. Generally, we should try to reduce the size of the page's tab ring rather than increasing it. ### Examples Examples of **incorrect** code for this rule: ```jsx
``` Examples of **correct** code for this rule: ```jsx