### Quick Start Migration with bun
Source: https://oxc.rs/docs/guide/usage/formatter/migrate-from-prettier
Installs Oxfmt and runs the migration and formatting commands using bun.
```bash
$ bun add -D oxfmt@latest && bunx oxfmt --migrate=prettier && bunx oxfmt
```
--------------------------------
### Quick Start Migration with npm
Source: https://oxc.rs/docs/guide/usage/formatter/migrate-from-prettier
Installs Oxfmt and runs the migration and formatting commands using npm.
```bash
$ npm add -D oxfmt@latest && npx oxfmt --migrate=prettier && npx oxfmt
```
--------------------------------
### Quick Start Migration with yarn
Source: https://oxc.rs/docs/guide/usage/formatter/migrate-from-prettier
Installs Oxfmt and runs the migration and formatting commands using yarn.
```bash
$ yarn add -D oxfmt@latest && yarn oxfmt --migrate=prettier && yarn oxfmt
```
--------------------------------
### Minimal Linter Code Example
Source: https://oxc.rs/docs/learn/architecture/linter
This example demonstrates the minimal setup required to create and run a linter using the oxlint crates. It shows how to initialize the `Runtime`, `Linter`, and `LintService`.
```rust
use oxc_linter::Linter;
use oxc_linter::service::LintService;
use oxc_linter::workspace::Runtime;
use std::sync::Arc;
#[tokio::main]
async fn main() {
let runtime = Arc::new(Runtime::new(Default::default()).unwrap());
let rules = Default::default();
let linter = Linter::new(rules);
let lint_service = LintService::new(runtime, linter);
lint_service.run().await;
}
```
--------------------------------
### Quick Start Migration with pnpm
Source: https://oxc.rs/docs/guide/usage/formatter/migrate-from-prettier
Installs Oxfmt and runs the migration and formatting commands using pnpm.
```bash
$ pnpm add -D oxfmt@latest && pnpm oxfmt --migrate=prettier && pnpm oxfmt
```
--------------------------------
### Install Oxlint with pnpm
Source: https://oxc.rs/docs/guide/usage/linter
Install Oxlint as a development dependency using pnpm. This is the recommended setup for integrating Oxlint into your project.
```sh
pnpm add -D oxlint
```
--------------------------------
### Install Rust Toolchain
Source: https://oxc.rs/docs/contribute/development
After installing Rust, run this command in the project root to ensure the correct Rust toolchain and components specified in `./rust-toolchain.toml` are installed.
```bash
rustup show
```
--------------------------------
### Per-file setup with before hook
Source: https://oxc.rs/docs/guide/usage/linter/writing-js-plugins
Illustrates how to perform per-file setup in the `before` hook when using `createOnce`, replacing the initialization within `create`.
```diff
- let classCount = 0;
+ let classCount;
return {
+ before() {
+ classCount = 0; // Reset counter
+ },
ClassDeclaration(node) {
classCount++;
if (classCount === 6) {
context.report({ message: "Too many classes", node });
}
},
};
```
--------------------------------
### Correct Code: Using hooks in Vitest
Source: https://oxc.rs/docs/guide/usage/linter/rules/vitest/require-hook
This example shows the correct way to use setup and teardown logic within Vitest by utilizing hooks like beforeEach and afterEach, adhering to the require-hook rule.
```javascript
import { database, isCity } from "../database";
import { Logger } from "../../../src/Logger";
import { loadCities } from "../api";
jest.mock("../api");
const initializeCityDatabase = () => {
database.addCity("Vienna");
database.addCity("San Juan");
database.addCity("Wellington");
};
const clearCityDatabase = () => {
database.clear();
};
beforeEach(() => {
initializeCityDatabase();
});
test("that persists cities", () => {
expect(database.cities.length).toHaveLength(3);
});
test("city database has Vienna", () => {
expect(isCity("Vienna")).toBeTruthy();
});
test("city database has San Juan", () => {
expect(isCity("San Juan")).toBeTruthy();
});
describe("when loading cities from the api", () => {
let consoleWarnSpy;
beforeEach(() => {
consoleWarnSpy = jest.spyOn(console, "warn");
loadCities.mockResolvedValue(["Wellington", "London"]);
});
it("does not duplicate cities", async () => {
await database.loadCities();
expect(database.cities).toHaveLength(4);
});
});
afterEach(() => {
clearCityDatabase();
});
```
--------------------------------
### Install cargo-binstall
Source: https://oxc.rs/docs/contribute/development
Install `cargo-binstall`, a tool that simplifies installing Rust binaries and is faster than building from source.
```bash
cargo install cargo-binstall
```
--------------------------------
### Install Oxfmt with bun
Source: https://oxc.rs/docs/guide/usage/formatter/quickstart
Install oxfmt as a development dependency using bun.
```sh
$ bun add -D oxfmt
```
--------------------------------
### Install Oxlint with bun
Source: https://oxc.rs/docs/guide/usage/linter/quickstart
Install oxlint as a dev dependency using bun.
```sh
$ bun add -D oxlint
```
--------------------------------
### Install Oxfmt with deno
Source: https://oxc.rs/docs/guide/usage/formatter/migrate-from-prettier
Installs the latest version of Oxfmt as a development dependency using deno.
```bash
$ deno add -D npm:oxfmt@latest
```
--------------------------------
### Correct Test Filename Example
Source: https://oxc.rs/docs/guide/usage/linter/rules/vitest/consistent-test-filename
This example demonstrates a file path that conforms to the rule's configuration, with a filename matching the expected pattern.
```text
__tests__/2.spec.ts
```
--------------------------------
### Install Oxfmt with pnpm
Source: https://oxc.rs/docs/guide/usage/formatter/quickstart
Install oxfmt as a development dependency using pnpm.
```sh
$ pnpm add -D oxfmt
```
--------------------------------
### Correct Vue Configuration Example
Source: https://oxc.rs/docs/guide/usage/linter/rules/vue/no-deprecated-vue-config-keycodes
This example demonstrates correct Vue configuration, avoiding the deprecated `Vue.config.keyCodes`. Ensure your Vue configuration does not rely on removed features.
```js
Vue.config.silent = true;
```
--------------------------------
### Correct code using require-hook rule
Source: https://oxc.rs/docs/guide/usage/linter/rules/jest/require-hook
This example demonstrates the correct usage of Jest hooks for setup and teardown logic, adhering to the require-hook rule.
```javascript
import { database, isCity } from "../database";
import { Logger } from "../../../src/Logger";
import { loadCities } from "../api";
jest.mock("../api");
const initializeCityDatabase = () => {
database.addCity("Vienna");
database.addCity("San Juan");
database.addCity("Wellington");
};
const clearCityDatabase = () => {
database.clear();
};
beforeEach(() => {
initializeCityDatabase();
});
test("that persists cities", () => {
expect(database.cities.length).toHaveLength(3);
});
test("city database has Vienna", () => {
expect(isCity("Vienna")).toBeTruthy();
});
test("city database has San Juan", () => {
expect(isCity("San Juan")).toBeTruthy();
});
describe("when loading cities from the api", () => {
let consoleWarnSpy;
beforeEach(() => {
consoleWarnSpy = jest.spyOn(console, "warn");
loadCities.mockResolvedValue(["Wellington", "London"]);
});
it("does not duplicate cities", async () => {
await database.loadCities();
expect(database.cities).toHaveLength(4);
});
});
afterEach(() => {
clearCityDatabase();
});
```
--------------------------------
### Install just
Source: https://oxc.rs/docs/contribute/development
Install `just`, a command runner used by OXC for project-specific commands. This command uses `cargo-binstall` for installation.
```bash
cargo binstall just -y
```
--------------------------------
### Install Oxlint with pnpm
Source: https://oxc.rs/docs/guide/usage/linter/quickstart
Install oxlint as a dev dependency using pnpm.
```sh
$ pnpm add -D oxlint
```
--------------------------------
### Install Oxfmt with yarn
Source: https://oxc.rs/docs/guide/usage/formatter/quickstart
Install oxfmt as a development dependency using yarn.
```sh
$ yarn add -D oxfmt
```
--------------------------------
### Install Oxfmt with npm
Source: https://oxc.rs/docs/guide/usage/formatter/quickstart
Install oxfmt as a development dependency using npm.
```sh
$ npm add -D oxfmt
```
--------------------------------
### Install Oxlint with npm
Source: https://oxc.rs/docs/guide/usage/linter/quickstart
Install oxlint as a dev dependency using npm.
```sh
$ npm add -D oxlint
```
--------------------------------
### Correct Getter Return Example
Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/getter-return
This example shows the correct way to implement a getter, ensuring it always returns a value.
```javascript
class Person {
get name() {
return this._name;
}
}
```
--------------------------------
### Install Oxlint with yarn
Source: https://oxc.rs/docs/guide/usage/linter/quickstart
Install oxlint as a dev dependency using yarn.
```sh
$ yarn add -D oxlint
```
--------------------------------
### Styled Components Output Example
Source: https://oxc.rs/docs/guide/usage/transformer/plugins
Example of styled-components output after transformation with default options.
```jsx
import styled from "styled-components";
const Button = styled.div.withConfig({
displayName: "Button",
componentId: "sc-1234567-0",
})(["color:blue;padding:10px;"]);
```
--------------------------------
### Install Oxfmt with pnpm
Source: https://oxc.rs/docs/guide/usage/formatter/migrate-from-prettier
Installs the latest version of Oxfmt as a development dependency using pnpm.
```bash
$ pnpm add -D oxfmt@latest
```
--------------------------------
### Styled Components Input Example
Source: https://oxc.rs/docs/guide/usage/transformer/plugins
Example of a styled-components input for transformation.
```jsx
import styled from "styled-components";
const Button = styled.div`
color: blue;
padding: 10px;
`;
```
--------------------------------
### Install coc-oxc for coc.nvim
Source: https://oxc.rs/docs/guide/usage/formatter/editors
Install the coc-oxc extension for the coc.nvim plugin manager.
```vim
:CocInstall coc-oxc
```
--------------------------------
### Incorrect Constructor Name Example
Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/new-cap
This example shows a function that is incorrectly used as a constructor because its name does not start with an uppercase letter.
```javascript
function foo(arg) {
return Boolean(arg);
}
```
--------------------------------
### Install oxfmt globally for Neovim
Source: https://oxc.rs/docs/guide/usage/formatter/editors
Install the oxfmt binary globally using npm. This is a prerequisite for configuring nvim-lspconfig.
```sh
npm i -g oxfmt
```
--------------------------------
### Incorrect Code Example for Unicode BOM Rule
Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/unicode-bom
This example shows code that would be flagged as incorrect by the unicode-bom rule when configured to disallow BOMs. No specific setup is required to trigger this.
```javascript
var a = 123;
```
--------------------------------
### Initialize Project Dependencies
Source: https://oxc.rs/docs/contribute/development
Run this command in the project root to install all necessary project dependencies using `just`.
```bash
just init
```
--------------------------------
### Correct Code Examples for prefer-spread
Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/prefer-spread
Examples of code that adheres to the prefer-spread rule, demonstrating the correct usage of spread syntax.
```javascript
// Using spread syntax
foo(...args);
obj.foo(...args);
// The `this` binding is different.
foo.apply(obj, args);
obj.foo.apply(null, args);
obj.foo.apply(otherObj, args);
// The argument list is not variadic.
// Those are warned by the `no-useless-call` rule.
foo.apply(undefined, [1, 2, 3]);
foo.apply(null, [1, 2, 3]);
obj.foo.apply(obj, [1, 2, 3]);
```
--------------------------------
### Check Project Build Readiness
Source: https://oxc.rs/docs/contribute/development
Use this command to verify that the entire project builds and runs correctly after setup.
```bash
just ready
```
--------------------------------
### Correct Binary Expressions
Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/no-constant-binary-expression
These examples demonstrate the correct way to write the binary expressions shown in the incorrect examples, ensuring they function as intended.
```javascript
const x = a + (b ?? c);
const isEmpty = x.length === 0;
```
--------------------------------
### Incorrect: Uppercase test title
Source: https://oxc.rs/docs/guide/usage/linter/rules/jest/prefer-lowercase-title
This example shows an incorrect usage where the test title starts with an uppercase letter.
```javascript
it("Adds 1 + 2 to equal 3", () => {
expect(sum(1, 2)).toBe(3);
});
```
--------------------------------
### Allow process.env Usage with Configuration
Source: https://oxc.rs/docs/guide/usage/linter/rules/node/no-process-env
This example shows correct code that imports configuration from a separate file instead of directly accessing `process.env`. This is the recommended approach.
```javascript
import config from "./config";
if (config.env === "development") {
//...
}
```
--------------------------------
### Initialize Oxfmt Configuration
Source: https://oxc.rs/docs/guide/usage/formatter/config
Run this command to generate a starter configuration file in the current directory. Oxfmt automatically detects configuration files like .oxfmtrc.json.
```sh
oxfmt --init
```
--------------------------------
### Disallow GET/HEAD with body in fetch()
Source: https://oxc.rs/docs/guide/usage/linter/rules/unicorn/no-invalid-fetch-options
This example shows incorrect usage where a body is provided with a GET request. This will throw a TypeError.
```javascript
const response = await fetch("/", { method: "GET", body: "foo=bar" });
```
--------------------------------
### Correct Code Examples for func-names (as-needed)
Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/func-names
These examples show function expressions that adhere to the 'as-needed' naming convention for the `func-names` rule.
```javascript
/* func-names: ["error", "as-needed"] */
const bar = function () {};
const cat = { meow: function () {} };
class C {
#bar = function () {};
baz = function () {};
}
quux ??= function () {};
(function bar() {
/* ... */
})();
export default function foo() {}
```
--------------------------------
### Ambiguous Slash Token Examples in JavaScript
Source: https://oxc.rs/docs/learn/ecmascript/grammar
Illustrates scenarios where a '/' token can be interpreted as either a division operator or the start of a regular expression literal. Understanding these examples is key to grasping JavaScript's lexical and syntactic grammar interaction.
```javascript
a / b;
a / / regex /;
a /= / regex /;
/ regex / / b;
/=/ / /=/;
```
--------------------------------
### Correct Code Examples (always option)
Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/operator-assignment
Examples of code that adheres to the 'always' configuration, demonstrating valid use of shorthand assignment operators and cases where they are not applicable.
```javascript
x = y;
x += y;
x = y * z;
x = x * y * z;
x[0] /= y;
x[foo()] = x[foo()] % 2;
x = y + x; // `+` is not always commutative (e.g. x = "abc")
```
--------------------------------
### Incorrect Comments for Capitalized-Comments Rule
Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/capitalized-comments
Examples of comments that violate the capitalized-comments rule when the 'always' option is active. These comments start with a lowercase letter.
```javascript
// lowercase comment
/* lowercase block comment */
```
--------------------------------
### Initialize Oxlint config file
Source: https://oxc.rs/docs/guide/usage/linter/quickstart
Create a default .oxlintrc.json configuration file.
```sh
oxlint --init
```
--------------------------------
### Restrict Specific Path with Custom Message
Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/no-restricted-imports
This example shows how to restrict the 'cluster' module and provides a custom message guiding users to an alternative.
```javascript
/* no-restricted-imports: ["error", { "paths": ["cluster"] }] */
import cluster from "cluster";
```
--------------------------------
### Root Configuration Example (.oxlintrc.json)
Source: https://oxc.rs/docs/guide/usage/linter/nested-config
Defines a base configuration with a 'no-debugger' rule at the project root.
```json
{
"rules": {
"no-debugger": "error"
}
}
```
--------------------------------
### Incorrect: Uppercase in nested describe with lowercaseFirstCharacterOnly
Source: https://oxc.rs/docs/guide/usage/linter/rules/jest/prefer-lowercase-title
This example shows an incorrect usage when `lowercaseFirstCharacterOnly` is enabled and a nested describe block starts with an uppercase letter.
```javascript
/* vitest/prefer-lowercase-title: ["error", { "lowercaseFirstCharacterOnly": true }] */
describe("MyClass", () => {
describe("MyMethod", () => {
it("does things", () => {
//
});
});
});
```
--------------------------------
### Incorrect Enum Initialization in TypeScript
Source: https://oxc.rs/docs/guide/usage/linter/rules/typescript/prefer-enum-initializers
This example shows an enum where the `Close` member implicitly gets a value. This is flagged by the rule because explicit initialization is required.
```typescript
enum Status {
Open = 1,
Close,
}
```
--------------------------------
### Correct Comments for Capitalized-Comments Rule
Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/capitalized-comments
Examples of comments that adhere to the capitalized-comments rule when the 'always' option is active. These comments start with a capital letter or a non-letter character.
```javascript
// Capitalized comment
/* Capitalized block comment */
// 123 - comments starting with non-letters are ignored
```
--------------------------------
### Using createOnce instead of create
Source: https://oxc.rs/docs/guide/usage/linter/writing-js-plugins
Shows the change from using the `create` method to `createOnce` when adopting Oxlint's alternative API.
```diff
- create(context) {
+ createOnce(context) {
```
--------------------------------
### Disallow GET/HEAD with body in new Request()
Source: https://oxc.rs/docs/guide/usage/linter/rules/unicorn/no-invalid-fetch-options
This example demonstrates incorrect usage with `new Request()`, providing a body for a GET method. This will also result in a TypeError.
```javascript
const request = new Request("/", { method: "GET", body: "foo=bar" });
```
--------------------------------
### Arrow Body Style: 'as-needed' - Correct Examples
Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/arrow-body-style
These examples show correct code when the 'as-needed' option is used, allowing concise bodies where possible.
```javascript
/* arrow-body-style: ["error", "as-needed"] */
/* ✔ Good: */
const foo1 = () => 0;
const foo2 = (retv, name) => {
retv[name] = true;
return retv;
};
const foo3 = () => {
bar();
};
```
--------------------------------
### Example: Partition Imports by Comment
Source: https://oxc.rs/docs/guide/usage/formatter/config-file-reference
Enable partitioning of imports using comments as delimiters. When true, comments will separate imports into distinct groups.
```javascript
import { b1, b2 } from "b";
// PARTITION
import { a } from "a";
import { c } from "c";
```
--------------------------------
### Ignore files matching a pattern
Source: https://oxc.rs/docs/guide/usage/linter/rules/unicorn/filename-case
Use the 'ignore' option with a regular expression to exclude specific filenames from the casing rule. This example ignores files starting with 'foo'.
```json
{
"unicorn/filename-case": [
"error",
{
"ignore": "^foo.*$"
}
]
}
```
--------------------------------
### Configuration: Custom message for 'className' prop
Source: https://oxc.rs/docs/guide/usage/linter/rules/react/forbid-dom-props
This configuration example demonstrates forbidding the 'className' prop and providing a custom message to guide users to use 'class' instead.
```javascript
["error", { "forbid": [{ "propName": "className", "message": "Use class instead" }] }]
```
--------------------------------
### Install Dependencies and Build Monorepo
Source: https://oxc.rs/docs/guide/usage/linter/type-aware
For monorepos, ensure dependencies are installed and dependent packages are built to make `.d.ts` files available before running type-aware linting.
```bash
pnpm install
pnpm -r build
oxlint --type-aware
```
--------------------------------
### Correct Vue Code: No Compiler Macro Imports
Source: https://oxc.rs/docs/guide/usage/linter/rules/vue/no-import-compiler-macros
This example demonstrates correct usage in Vue 3's `
```
--------------------------------
### Initialize Oxlint Configuration
Source: https://oxc.rs/docs/guide/usage/linter/cli
Use the `--init` flag to generate a default Oxlint configuration file in the current directory.
```bash
oxlint --init
```
--------------------------------
### JavaScript AST JSON Example
Source: https://oxc.rs/docs/learn/parser_in_rust/ast
This JSON represents the AST for the JavaScript code 'var a'. It shows the hierarchical structure of nodes like Program, VariableDeclaration, and Identifier, along with their start and end offsets.
```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"
}
```
--------------------------------
### Migrate from Prettier
Source: https://oxc.rs/docs/guide/usage/formatter/quickstart
Run the migration command to convert Prettier configurations to Oxfmt format.
```sh
oxfmt --migrate prettier
```
--------------------------------
### Incorrect Vue Code: Lifecycle Hook After Await
Source: https://oxc.rs/docs/guide/usage/linter/rules/vue/no-lifecycle-after-await
This example shows incorrect usage where an `onMounted` hook is called after an `await` statement in Vue's `setup()` function, which can lead to the hook being registered too late.
```vue
```
--------------------------------
### Incorrect Vue Code: Importing Compiler Macros
Source: https://oxc.rs/docs/guide/usage/linter/rules/vue/no-import-compiler-macros
This example shows incorrect usage where Vue compiler macros like `defineProps` and `withDefaults` are explicitly imported. These should not be imported as they are globally available in `
```
--------------------------------
### Initialize Request with LSP Options
Source: https://oxc.rs/docs/guide/usage/linter/lsp-config-reference
Example of an `initialize` request sent by a client to configure Oxlint LSP options, including workspace URI and specific options like `unusedDisableDirectives` and `typeAware`.
```json
{
"processId": 123,
"rootUri": null,
"workspaceFolders": [],
"capabilities": {},
"initializationOptions": [
{
"workspaceUri": "file:///home/user/project",
"options": {
"unusedDisableDirectives": "deny",
"typeAware": true
}
}
]
}
```
--------------------------------
### Correct Vue Code: Lifecycle Hook Before Await
Source: https://oxc.rs/docs/guide/usage/linter/rules/vue/no-lifecycle-after-await
This example demonstrates correct usage where the `onMounted` hook is registered synchronously before any `await` statements within Vue's `setup()` function, ensuring proper registration.
```vue
```
--------------------------------
### Run Oxlint after initialization
Source: https://oxc.rs/docs/guide/usage/linter/quickstart
Run Oxlint after creating or customizing the configuration file.
```sh
oxlint
```
--------------------------------
### Incorrect Code: Top-level expressions in Vitest
Source: https://oxc.rs/docs/guide/usage/linter/rules/vitest/require-hook
This example demonstrates incorrect usage where setup and teardown logic are placed at the top level of a test file or directly within a describe block, violating the require-hook rule.
```javascript
import { database, isCity } from "../database";
import { Logger } from "../../../src/Logger";
import { loadCities } from "../api";
jest.mock("../api");
const initializeCityDatabase = () => {
database.addCity("Vienna");
database.addCity("San Juan");
database.addCity("Wellington");
};
const clearCityDatabase = () => {
database.clear();
};
initializeCityDatabase();
test("that persists cities", () => {
expect(database.cities.length).toHaveLength(3);
});
test("city database has Vienna", () => {
expect(isCity("Vienna")).toBeTruthy();
});
test("city database has San Juan", () => {
expect(isCity("San Juan")).toBeTruthy();
});
describe("when loading cities from the api", () => {
let consoleWarnSpy = jest.spyOn(console, "warn");
loadCities.mockResolvedValue(["Wellington", "London"]);
it("does not duplicate cities", async () => {
await database.loadCities();
expect(database.cities).toHaveLength(4);
});
});
clearCityDatabase();
```
--------------------------------
### Correct Import of Vitest
Source: https://oxc.rs/docs/guide/usage/linter/rules/vitest/no-import-node-test
This example demonstrates the correct way to import and use `vitest` for testing. This code adheres to the rule's requirements.
```javascript
import { test, expect } from "vitest";
test("foo", () => {
expect(1).toBe(1);
});
```
--------------------------------
### Example: Partition Imports by Newline
Source: https://oxc.rs/docs/guide/usage/formatter/config-file-reference
Enable partitioning of imports using empty lines as delimiters. When true, the formatter will not reorder imports separated by blank lines, preserving logical grouping.
```javascript
import { b1, b2 } from "b";
import { a } from "a";
import { c } from "c";
```
--------------------------------
### Incorrect code violating require-hook rule
Source: https://oxc.rs/docs/guide/usage/linter/rules/jest/require-hook
This example shows code that violates the require-hook rule by placing setup and teardown logic at the top level or directly within describe blocks, rather than using Jest hooks.
```javascript
import { database, isCity } from "../database";
import { Logger } from "../../../src/Logger";
import { loadCities } from "../api";
jest.mock("../api");
const initializeCityDatabase = () => {
database.addCity("Vienna");
database.addCity("San Juan");
database.addCity("Wellington");
};
const clearCityDatabase = () => {
database.clear();
};
initializeCityDatabase();
test("that persists cities", () => {
expect(database.cities.length).toHaveLength(3);
});
test("city database has Vienna", () => {
expect(isCity("Vienna")).toBeTruthy();
});
test("city database has San Juan", () => {
expect(isCity("San Juan")).toBeTruthy();
});
describe("when loading cities from the api", () => {
let consoleWarnSpy = jest.spyOn(console, "warn");
loadCities.mockResolvedValue(["Wellington", "London"]);
it("does not duplicate cities", async () => {
await database.loadCities();
expect(database.cities).toHaveLength(4);
});
});
clearCityDatabase();
```
--------------------------------
### Print Parsed Code with esrap
Source: https://oxc.rs/docs/guide/usage/parser
This example demonstrates how to parse JavaScript code using oxc-parser and then print the resulting Abstract Syntax Tree (AST) back into code using the esrap library. Ensure both 'oxc-parser' and 'esrap' are installed.
```js
import { print } from "esrap";
import ts from "esrap/languages/ts";
import { parseSync } from "oxc-parser";
const { program } = parseSync("test.js", 'alert("hello oxc & esrap");');
const { code } = print(program, ts());
console.log(code); // alert("hello oxc & esrap");
```
--------------------------------
### Basic Oxfmt Configuration
Source: https://oxc.rs/docs/guide/usage/formatter/migrate-from-prettier
Example of a basic Oxfmt configuration file using JSONC format.
```jsonc
{
"$schema": "./node_modules/oxfmt/configuration_schema.json",
"printWidth": 80,
}
```
--------------------------------
### Example Type Size Output
Source: https://oxc.rs/docs/learn/parser_in_rust/ast
Shows an example output from the `RUSTFLAGS=-Zprint-type-sizes` command, detailing the size and alignment of a specific type (`ast::js::Statement`) and its variants. This information is crucial for understanding memory usage and identifying potential optimizations.
```text
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
```
--------------------------------
### Start oxfmt Language Server
Source: https://oxc.rs/docs/guide/usage/formatter/editors
Start the oxfmt language server from the command line. This is useful for editors that support the Language Server Protocol but don't have a dedicated plugin.
```sh
oxfmt --lsp
```
--------------------------------
### Format Files
Source: https://oxc.rs/docs/guide/usage/formatter
Run the `fmt` script to format files in your project.
```sh
pnpm run fmt
```
--------------------------------
### Correct Path Construction with path.join()
Source: https://oxc.rs/docs/guide/usage/linter/rules/node/no-path-concat
Demonstrates the correct way to construct file paths using path.join() with __dirname and __filename. This ensures cross-platform compatibility.
```javascript
const fullPath1 = path.join(__dirname, "foo.js");
const fullPath2 = path.join(__filename, "foo.js");
const fullPath3 = __dirname + ".js";
const fullPath4 = __filename + ".map";
const fullPath5 = `${__dirname}_foo.js`;
const fullPath6 = `${__filename}.test.js`;
```
--------------------------------
### Correct code for prefer-snapshot-hint rule ('multi')
Source: https://oxc.rs/docs/guide/usage/linter/rules/jest/prefer-snapshot-hint
Shows correct usage of snapshot matchers with hints, adhering to the 'multi' configuration. This example is useful when multiple snapshot matchers are present in a scope.
```javascript
const snapshotOutput = ({ stdout, stderr }, hints) => {
expect(stdout).toMatchSnapshot({}, `stdout: ${hints.stdout}`);
expect(stderr).toMatchSnapshot({}, `stderr: ${hints.stderr}`);
};
describe("cli", () => {
describe("--version flag", () => {
it("prints the version", async () => {
snapshotOutput(await runCli(["--version"])), {
stdout: "version string",
stderr: "empty",
};
});
});
describe("--config flag", () => {
it("reads the config", async () => {
const { stdout } = await runCli(["--config", "jest.config.js"]);
expect(stdout).toMatchSnapshot();
});
it("prints nothing to stderr", async () => {
const { stderr } = await runCli(["--config", "jest.config.js"]);
expect(stderr).toMatchInlineSnapshot();
});
describe("when the file does not exist", () => {
it("throws an error", async () => {
await expect(
runCli(["--config", "does-not-exist.js"]),
).rejects.toThrowErrorMatchingSnapshot();
});
});
});
});
```
--------------------------------
### Per-Extension Configuration
Source: https://oxc.rs/docs/guide/usage/linter/rules/import/extensions
Demonstrates configuring specific extensions to be always required or never required, and how unconfigured extensions are handled.
```javascript
// Configuration: { "vue": "always", "ts": "never" }
import Component from "./Component.vue"; // ✓ OK - .vue configured as "always"
import utils from "./utils"; // ✓ OK - .ts configured as "never"
import styles from "./styles.css"; // ✓ OK - .css not configured, ignored
```
--------------------------------
### Run Binary with rust-lldb
Source: https://oxc.rs/docs/contribute/debugging
Launch the compiled release binary using rust-lldb for debugging. Press 'r' to start the program execution within the debugger.
```bash
rust-lldb -- ./target/release/oxlint
```
--------------------------------
### Tokenization Example Output
Source: https://oxc.rs/docs/learn/parser_in_rust/lexer
Illustrates the expected output when tokenizing an identifier or a string literal, showing the resulting `Token` structure with its kind and value.
```text
Token { kind: Kind::Identifier, start: 0, end: 2, value: TokenValue::String("foo") }
Token { kind: Kind::String, start: 0, end: 4, value: TokenValue::String("bar") }
```
--------------------------------
### Correct Code Examples for no-zero-fractions
Source: https://oxc.rs/docs/guide/usage/linter/rules/unicorn/no-zero-fractions
These examples show the correct usage of numbers, adhering to the unicorn/no-zero-fractions rule by avoiding zero fractions. Whole numbers and non-zero fractions are preferred.
```javascript
const foo = 1;
const foo = -1;
const foo = 123456;
const foo = 1.1;
```
--------------------------------
### Build and Run Oxlint CLI
Source: https://oxc.rs/docs/contribute/linter
Build the Oxlint CLI and then execute it using Node.js against a target codebase. This is useful for testing your changes on a large project.
```bash
# build the oxlint cli in the oxc repo
just oxlint-node
# and then in the directory of the codebase you want to test with, run oxlint with node:
node /apps/oxlint/dist/cli.js
```
```bash
# You can also pass flags to it, like -D to enable a specific rule, and --disable-x-plugin to turn off default plugins:
node /apps/oxlint/dist/cli.js -D rulename --disable-unicorn-plugin --disable-oxc-plugin --disable-typescript-plugin
```
--------------------------------
### Correct Client Component Examples
Source: https://oxc.rs/docs/guide/usage/linter/rules/nextjs/no-async-client-component
These examples show valid ways to structure client components in Next.js, including synchronous components and handling async operations within effects or event handlers.
```javascript
"use client"
// Regular synchronous component
export default function MyComponent() {
return <>>
}
```
```javascript
"use client"
// Handling async operations in effects
export default function MyComponent() {
useEffect(() => {
async function fetchData() {
// async operations here
}
fetchData();
}, []);
return <>>
}
```
```javascript
"use client"
// Async operations in event handlers
export default function MyComponent() {
const handleClick = async () => {
// async operations here
}
return
}
```
--------------------------------
### Disallow export in Vue
```
--------------------------------
### Example ESLint Configuration
Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/arrow-body-style
Configure the arrow-body-style rule with the 'as-needed' option and requireReturnForObjectLiteral set to true.
```json
{
"arrow-body-style": ["error", "as-needed", { "requireReturnForObjectLiteral": true }]
}
```
--------------------------------
### Correct JSX Spread Examples
Source: https://oxc.rs/docs/guide/usage/linter/rules/react/jsx-props-no-spread-multi
These examples demonstrate correct usage where props are spread only once, either before or after other attributes.
```jsx
```
```jsx
```
--------------------------------
### Compiler Frontend Phases
Source: https://oxc.rs/docs/learn/parser_in_rust/intro
Illustrates the typical stages involved in a compiler frontend, from source text to an Abstract Syntax Tree (AST).
```text
Source Text --> Lexer --> Token --> Parser --> AST
```
--------------------------------
### Chained Promises Example
Source: https://oxc.rs/docs/guide/usage/linter/rules/promise/no-nesting
An example of correctly chained promises, demonstrating a flat structure that avoids nesting.
```javascript
doThing()
.then(() => Promise.resolve(1))
.then(() => Promise.resolve(2));
```
--------------------------------
### Install Oxlint Globally for Neovim
Source: https://oxc.rs/docs/guide/usage/linter/editors
Install the `oxlint` package globally using npm. This is a prerequisite for configuring `nvim-lspconfig`.
```sh
npm i -g oxlint
```
--------------------------------
### Run Conformance Tests (Alternative)
Source: https://oxc.rs/docs/contribute/parser
An alternative command to run the conformance test suite, potentially with additional options or logging.
```bash
just coverage
```
--------------------------------
### AST Node Structure Example
Source: https://oxc.rs/docs/contribute/parser/ast
Illustrates the consistent pattern of AST nodes, including source location, visitor generation, and lifetime management.
```rust
#[ast(visit)]
pub struct FunctionDeclaration<'a> {
pub span: Span,
pub id: Option>,
pub generator: bool,
pub r#async: bool,
pub params: FormalParameters<'a>,
pub body: Option,
pub type_parameters: Option>,
pub return_type: Option>,
}
```
--------------------------------
### Correct JSX Nesting Example
Source: https://oxc.rs/docs/guide/usage/linter/rules/react/jsx-max-depth
This example shows JSX code that adheres to the maximum nesting depth rule.
```jsx
const Component = () => (
);
```
--------------------------------
### Incorrect JSX Nesting Example
Source: https://oxc.rs/docs/guide/usage/linter/rules/react/jsx-max-depth
This example demonstrates JSX code that violates the maximum nesting depth rule.
```jsx
const Component = () => (
);
```
--------------------------------
### Styled Components Supported Import Patterns
Source: https://oxc.rs/docs/guide/usage/transformer/plugins
Demonstrates various import patterns supported by the styled-components plugin.
```javascript
// Default import
import styled from "styled-components";
// Namespace import
import * as styled from "styled-components";
// Named imports
import { createGlobalStyle, css, keyframes } from "styled-components";
// Native and primitives
import styled from "styled-components/native";
import styled from "styled-components/primitives";
```
--------------------------------
### Incorrect Code Examples for prefer-spread
Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/prefer-spread
Examples of code that violates the prefer-spread rule, using `.apply()` in various contexts.
```javascript
foo.apply(undefined, args);
foo.apply(null, args);
obj.foo.apply(obj, args);
```
--------------------------------
### Correct Promise Testing with resolves
Source: https://oxc.rs/docs/guide/usage/linter/rules/jest/prefer-expect-resolves
Examples demonstrating the preferred method of testing promises using `await expect(...).resolves`. This approach ensures consistent behavior and clearer error reporting.
```javascript
it("passes", async () => {
await expect(someValue()).resolves.toBe(true);
});
```
```javascript
it("is true", async () => {
const myPromise = Promise.resolve(true);
await expect(myPromise).resolves.toBe(true);
});
```
--------------------------------
### Add migrate-oxlint skill
Source: https://oxc.rs/docs/guide/usage/linter/migrate-from-eslint
Install the `migrate-oxlint` skill for an interactive migration experience. This command adds the skill to your local `skills` environment.
```bash
npx skills add https://github.com/oxc-project/oxc --skill migrate-oxlint
```
--------------------------------
### Correct Code Examples for prefer-destructuring
Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/prefer-destructuring
Examples of code that adheres to the prefer-destructuring rule using array and object destructuring.
```javascript
// With `array` enabled
const [foo] = array;
const arr = array[someIndex];
[bar.baz] = array;
// With `object` enabled
const { baz } = object;
const obj = object.bar;
```
--------------------------------
### Incorrect Code Examples for prefer-destructuring
Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/prefer-destructuring
Examples of code that violates the prefer-destructuring rule when array or object destructuring is enabled.
```javascript
// With `array` enabled
const foo = array[0];
bar.baz = array[0];
// With `object` enabled
const qux = object.qux;
const quux = object["quux"];
```
--------------------------------
### Example of extending Object.prototype
Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/no-extend-native
This example demonstrates how extending Object.prototype can lead to unexpected behavior when iterating over object properties.
```javascript
// 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);
}
```
--------------------------------
### Incorrect Getter Return Examples
Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/getter-return
These examples demonstrate incorrect usage where getters do not return a value, which will be flagged by the rule.
```javascript
class Person {
get name() {
// no return
}
}
const obj = {
get foo() {
// object getter are also checked
},
};
```
--------------------------------
### Install CMake via Homebrew
Source: https://oxc.rs/docs/contribute/development
For macOS users with Homebrew, use this command to install CMake, a dependency for building the project.
```bash
brew install cmake
```
--------------------------------
### Correct code for prefer-prototype-methods
Source: https://oxc.rs/docs/guide/usage/linter/rules/unicorn/prefer-prototype-methods
Examples of code that adhere to the `prefer-prototype-methods` rule. These examples correctly borrow methods from their respective prototypes.
```javascript
const array = Array.prototype.slice.apply(bar);
const type = Object.prototype.toString.call(foo);
Reflect.apply(Array.prototype.forEach, arrayLike, [callback]);
const maxValue = Math.max.apply(Math, numbers);
```
--------------------------------
### Format files with npm
Source: https://oxc.rs/docs/guide/usage/formatter/quickstart
Run the 'fmt' npm script to format files in the current directory.
```sh
npm run fmt
```
--------------------------------
### Incorrect JSX Spread Example
Source: https://oxc.rs/docs/guide/usage/linter/rules/react/jsx-props-no-spread-multi
This example shows incorrect usage where the same props object is spread twice, which violates the rule.
```jsx
```
--------------------------------
### Conditional Unnesting Example
Source: https://oxc.rs/docs/guide/usage/linter/rules/promise/no-nesting
This example shows a scenario where unnesting would cause a variable to be undefined, thus it's not a violation.
```javascript
doThing().then((a) => getB(a).then((b) => getC(a, b)));
```
--------------------------------
### Correct use of flatMap()
Source: https://oxc.rs/docs/guide/usage/linter/rules/unicorn/prefer-array-flat-map
This example demonstrates the preferred and more efficient way to achieve the same result using `.flatMap()`.
```javascript
const bar = [1, 2, 3].flatMap((i) => [i]);
```
--------------------------------
### Enable Plugin with CLI
Source: https://oxc.rs/docs/guide/usage/linter/plugins
Enable the 'import' plugin directly from the command line interface. This is useful for quick checks or temporary configurations.
```bash
oxlint --import-plugin
```
--------------------------------
### Incorrect Jest Code Examples
Source: https://oxc.rs/docs/guide/usage/linter/rules/jest/prefer-to-be
Examples of code that violates the `prefer-to-be` rule. These use `toEqual` or `toStrictEqual` for primitive comparisons.
```javascript
expect(value).not.toEqual(5);
expect(getMessage()).toStrictEqual("hello world");
expect(loadMessage()).resolves.toEqual("hello world");
```
--------------------------------
### Correct Usage with Allowed Console Method
Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/no-console
This example demonstrates correct code when 'console.info' is explicitly allowed by the no-console rule configuration.
```javascript
console.info("foo");
```
--------------------------------
### Example of alternative fallthrough comment
Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/no-fallthrough
This example shows an alternative comment format that is also recognized for indicating intentional fallthrough.
```javascript
switch (foo) {
case 1:
doSomething();
// fall through
case 2:
doSomethingElse();
}
```
--------------------------------
### Run the ESLint flat config migration tool
Source: https://oxc.rs/docs/guide/usage/linter/migrate-from-eslint
Execute the `@oxlint/migrate` tool to automatically convert ESLint flat configuration files to Oxlint's format. This tool preserves rule severities, options, and path-specific overrides.
```bash
npx @oxlint/migrate
```
--------------------------------
### Example of intentional fallthrough comment
Source: https://oxc.rs/docs/guide/usage/linter/rules/eslint/no-fallthrough
This example illustrates the use of a comment to explicitly mark intentional fallthrough between case statements.
```javascript
switch (foo) {
case 1:
doSomething();
// falls through
case 2:
doSomethingElse();
}
```
--------------------------------
### Per-Extension Configuration with Ignore Packages
Source: https://oxc.rs/docs/guide/usage/linter/rules/import/extensions
Shows how to ignore package imports and configure specific extensions for non-package imports.
```javascript
// Configuration: ["ignorePackages", { "js": "never", "ts": "never" }]
import foo from "./foo"; // ✓ OK - no extension
import bar from "lodash/fp"; // ✓ OK - package import, ignored (ignorePackages sets this to true)
```
--------------------------------
### Basic CLI usage
Source: https://oxc.rs/docs/guide/usage/formatter/quickstart
The basic command structure for oxfmt. Running without arguments formats the current directory.
```sh
oxfmt [OPTIONS] [PATH]...
```
--------------------------------
### Correct img alt text examples
Source: https://oxc.rs/docs/guide/usage/linter/rules/jsx_a11y/img-redundant-alt
These examples show valid 'img' alt text that avoids redundant words. The first example provides descriptive text. The second passes because 'aria-hidden' is set, and the third passes because 'photo' is a variable, not a literal redundant word.
```jsx
```
```jsx
```
```jsx
```