GritQL plugin examples
These GritQL plugins solve common linting problems, and each one demonstrates a GritQL feature. For an introduction to GritQL syntax and the plugin system, read the Plugins guide and the GritQL reference first.
To use an example, save the GritQL snippet to a .grit file in your project and register it in your configuration:
{ "plugins": ["./plugins/your-rule.grit"]}Each example also links to the playground, where you can try it.
JavaScript and TypeScript
Section titled “JavaScript and TypeScript”Require strict equality except against null
Section titled “Require strict equality except against null”GritQL patterns can have conditions in a where clause. Inside a where block, the match operator <: tests whether a variable matches a pattern, and the not keyword negates the test. Every condition in a comma-separated list must be true for the pattern to match.
This pattern matches any == comparison, and uses two not conditions to skip the comparisons where either operand is the literal null, since == null is the one idiomatic use of loose equality:
`$left == $right` where { $right <: not `null`, $left <: not `null`, register_diagnostic( span = $left, message = "Use `===` instead of `==`. Loose equality is only acceptable when comparing against `null`.", severity = "warn" )}Matched, because neither side is null:
if (x == 1) {}if (x == "hello") {}Not matched, because one side is null:
if (x == null) {}if (null == x) {}Try this example in the playground
Ban forEach
Section titled “Ban forEach”The spread metavariable $... matches zero or more arguments or list elements without binding them. The as keyword binds the whole matched node to a variable, so you can reference it later, typically as the diagnostic span.
This pattern uses $... to match .forEach() calls with any number of arguments, and as $call to report the whole expression with a suggestion to use for...of instead:
`$collection.forEach($...)` as $call where { register_diagnostic( span = $call, message = "Prefer `for...of` over `.forEach()`. It supports `break`, `continue`, and `await`." )}const items = [1, 2, 3];items.forEach((item) => console.log(item));items.forEach((item, index) => { console.log(index, item);});for (const item of items) { console.log(item);}Both .forEach() calls are matched (lines 2 and 3). The for...of loop on line 6 is not matched.
Try this example in the playground
Ban specific packages
Section titled “Ban specific packages”The or operator matches if any of its child patterns match, which lets you list several banned package names. The anonymous metavariable $_ matches any node without creating a named binding, which is useful when you do not need the value.
This pattern matches any import statement, ignores the imported bindings with $_, and checks whether the source string matches one of the banned packages:
`import $_ from $source` where { $source <: or { `'lodash'`, `'underscore'`, `'moment'` }, register_diagnostic( span = $source, message = "This package is not allowed. Use the approved alternative instead." )}import _ from "lodash";import dayjs from "dayjs";import moment from "moment";import { merge } from "underscore";Lines 1, 3, and 4 are matched. Line 2 (dayjs) is not in the banned list.
Try this example in the playground
To also catch require() calls, match both import styles with a top-level or:
or { `import $_ from $source`, `require($source)`} where { $source <: or { `'lodash'`, `'underscore'`, `'moment'` }, register_diagnostic( span = $source, message = "This package is not allowed. Use the approved alternative instead." )}import _ from "lodash";import dayjs from "dayjs";const moment = require("moment");const utils = require("lodash");The banned packages are matched in both the import and the require() form. dayjs on line 2 is not in the list.
Try this example in the playground
Ban new Date() with arguments
Section titled “Ban new Date() with arguments”When $... is the only argument in a code snippet, it matches zero or more arguments. When you add a named metavariable before it, as in $first, $..., the pattern requires at least one argument, because $first must bind to something.
This pattern allows new Date(), which returns the current date, and flags new Date("2024-01-15") and other calls that pass a date, so that your project uses its own date utility instead:
`new Date($first, $...)` as $expr where { register_diagnostic( span = $expr, message = "Avoid the `Date` constructor for parsing. Use the project's date utility instead." )}const now = new Date();const parsed = new Date("2024-01-15");const custom = new Date(2024, 0, 15);const fromTs = new Date(1705276800000);Line 1 (new Date() without arguments) is not matched. Lines 2-4 have at least one argument, so they trigger the diagnostic.
Try this example in the playground
Ban eval() and the Function constructor
Section titled “Ban eval() and the Function constructor”A top-level or combines unrelated syntax patterns into a single plugin rule. Bind each arm with as $match to give every arm the same variable name, so that the shared where clause can reference it even though the arms match different syntax.
This pattern combines eval() calls and new Function() constructors into one rule:
or { `eval($code)` as $match, `new Function($...)` as $match} where { register_diagnostic( span = $match, message = "Dynamic code evaluation is not allowed. Avoid `eval()` and `new Function()`." )}eval("alert(1)");const fn = new Function("a", "b", "return a + b");const safe = JSON.parse(data);Lines 1 and 2 are matched. Line 3 calls JSON.parse, which neither arm matches.
Try this example in the playground
Ban nested ternaries
Section titled “Ban nested ternaries”Instead of matching code snippets, you can match Biome’s concrete syntax tree (CST) nodes directly. Each node type has a unique PascalCase name, such as JsConditionalExpression. The contains modifier searches the whole subtree of a matched node, so it finds nested structures at any depth.
This pattern finds any ternary that contains another ternary:
engine biome(1.0)language js(typescript, jsx)
JsConditionalExpression() as $outer where { $outer <: contains JsConditionalExpression() as $inner, register_diagnostic( span = $inner, message = "Nested ternary expressions are not allowed. Use `if`/`else` instead." )}const a = x ? 1 : 0;const b = x ? (y ? 1 : 2) : 0;const c = x ? 1 : y ? 2 : 3;Line 1 has a single ternary and is not matched. Lines 2 and 3 each contain a ternary inside another ternary.
Try this example in the playground
Limit the number of function parameters
Section titled “Limit the number of function parameters”This pattern matches JsParameters() and uses a regex to check whether the parameter list contains three or more commas, which means four or more parameters:
engine biome(1.0)language js(typescript, jsx)
JsParameters() as $params where { $params <: r".*,.*,.*,.*", register_diagnostic( span = $params, message = "Functions should not have more than 3 parameters. Use an options object instead.", severity = "warn" )}function ok(a, b, c) {}function tooMany(a, b, c, d) {}const arrow = (a, b, c, d, e) => {};ok has three parameters and is not matched. tooMany and arrow have four or more parameters and are matched.
Try this example in the playground
Ban empty catch blocks
Section titled “Ban empty catch blocks”CST nodes can be nested in a pattern to express structural constraints. This pattern matches a JsCatchClause whose body field is a JsBlockStatement with an empty statements list ([]). It reads almost like a type assertion: “a catch clause containing a block with no statements.”
engine biome(1.0)language js(typescript, jsx)
JsCatchClause(body = JsBlockStatement(statements = [])) as $catch where { register_diagnostic( span = $catch, message = "Empty catch blocks are not allowed. Handle the error or add a comment explaining why it is ignored." )}try { riskyOperation();} catch (e) {}
try { anotherOp();} catch (e) { console.error(e);}The first catch block, on line 3, is empty and matched. The second one contains a statement and is not matched.
Try this example in the playground
Ban the any type
Section titled “Ban the any type”Some CST nodes are specific to TypeScript. The TsAnyType node represents the any keyword wherever it appears as a type annotation. Matching this node finds every occurrence: in variable declarations, function parameters, return types, and generic arguments.
engine biome(1.0)language js(typescript)
TsAnyType() as $any where { register_diagnostic( span = $any, message = "Don't use `any`. Use `unknown`, a specific type, or a generic instead.", severity = "warn" )}let x: any = 1;function foo(x: any): any { return x;}const arr: Array<any> = [];let safe: unknown = 1;Every any annotation on lines 1, 2, and 5 is matched. The unknown on line 6 is a different type and is not matched.
Try this example in the playground
Require const instead of let
Section titled “Require const instead of let”let is a keyword, not a syntax node, so this pattern matches JsVariableStatement() and uses a regex to select only the statements whose text starts with let:
engine biome(1.0)language js(typescript, jsx)
JsVariableStatement() as $stmt where { $stmt <: r"let.*", register_diagnostic( span = $stmt, message = "Prefer `const` unless the variable is reassigned.", severity = "hint" )}let x = 1;let y = "hello";const z = true;Both let statements (lines 1 and 2) are matched. The const statement on line 3 is not matched, because its text starts with const.
Try this example in the playground
Ban dangerouslySetInnerHTML
Section titled “Ban dangerouslySetInnerHTML”GritQL snippet patterns also work in JSX. This pattern matches the dangerouslySetInnerHTML prop on any element and with any value:
`dangerouslySetInnerHTML=$value` as $attr where { register_diagnostic( span = $attr, message = "Do not use `dangerouslySetInnerHTML`. Sanitize content and render it safely instead." )}Matched, because the elements use the prop:
<div dangerouslySetInnerHTML={{ __html: content }} /><p dangerouslySetInnerHTML={{ __html: text }}></p>Not matched, because the element does not use dangerouslySetInnerHTML:
<div className="safe">{content}</div>Try this example in the playground
Ban inline style props
Section titled “Ban inline style props”The same approach bans inline style props, so that your project uses CSS classes or CSS-in-JS instead:
`style=$value` as $attr where { register_diagnostic( span = $attr, message = "Avoid inline `style` props. Use a CSS class or a styled component instead.", severity = "warn" )}Matched, because the elements use an inline style prop:
<button style={{ color: "red" }}>Click</button><div style={{ margin: 0, padding: 10 }}>Content</div>Not matched, because the element uses className:
<span className="highlight">OK</span>Try this example in the playground
Ban !important
Section titled “Ban !important”By default, GritQL patterns target JavaScript. The language css directive at the top of a .grit file switches to CSS, and the engine biome(1.0) directive tells GritQL to use Biome’s syntax tree, where the node names in this pattern come from. The !important modifier is a CssDeclarationImportant() node, so this pattern uses contains to find any declaration that includes it:
engine biome(1.0)language css
CssDeclarationWithSemicolon() as $decl where { $decl <: contains CssDeclarationImportant(), register_diagnostic( span = $decl, message = "Avoid `!important`. Increase selector specificity or restructure your styles instead." )}.button { color: red !important; display: flex;}.override { margin: 0 !important;}Lines 2 and 6 contain !important declarations and are matched.
Try this example in the playground
Ban hardcoded colors
Section titled “Ban hardcoded colors”Regex patterns use the r"..." syntax. They match the text content of a node rather than its syntactic structure, which is useful for values such as hex color codes that have no dedicated syntax node. This pattern and the next ones use only code snippets, so they need only the language css directive.
This pattern uses a regex to match any hex color in color declarations, so that your project uses CSS custom properties instead:
language css;
`color: $value` as $decl where { $value <: r"#[0-9a-fA-F]+", register_diagnostic( span = $value, message = "Don't use hardcoded hex colors. Use a CSS custom property (e.g. `var(--color-primary)`) instead.", severity = "warn" )}.header { color: #ff0000; background: var(--bg-primary);}.text { color: #1a2b3c;}Lines 2 and 6 use hardcoded hex colors and are matched. The var() reference on line 3 is not a hex value and is not matched.
Try this example in the playground
To also catch rgb() and hsl() functions, combine multiple regex patterns
with or:
language css;
`color: $value` as $decl where { $value <: or { r"#[0-9a-fA-F]+", r"rgba?\(.*\)", r"hsla?\(.*\)" }, register_diagnostic( span = $value, message = "Don't use hardcoded colors. Use a CSS custom property instead.", severity = "warn" )}Matched, because the values are hex, rgb(), and hsl() colors:
.header { color: #ff0000; background: var(--bg-primary);}.alert { color: rgb(255, 0, 0);}.text { color: hsl(200, 50%, 50%);}.safe { color: var(--text-primary);}The var() references on lines 3 and 12 do not match any of the regex patterns.
Try this example in the playground
Ban specific CSS properties
Section titled “Ban specific CSS properties”A top-level or lists alternative snippet patterns. Each arm matches independently, so you can ban several CSS properties by listing them:
language css;
or { `float: $value`, `clear: $value`} as $decl where { register_diagnostic( span = $decl, message = "The `float` and `clear` properties are not allowed. Use Flexbox or Grid for layout." )}.sidebar { float: left; width: 200px;}.clearfix { clear: both;}.modern { display: grid;}float on line 2 and clear on line 6 are matched. The .modern rule uses display: grid, which is not in the banned list.
Try this example in the playground
Require camelCase JSON keys
Section titled “Require camelCase JSON keys”The language json directive, used with engine biome(1.0), targets JSON files. JSON snippets with metavariables are not supported, so use the CST node JsonMemberName() to match any key. Combine it with a regex and or to enforce a naming convention.
This pattern flags any key that contains an underscore or starts with an uppercase letter, since neither is camelCase:
engine biome(1.0)language json
JsonMemberName() as $name where { $name <: or { r".*_.*", r".[A-Z].*" }, register_diagnostic( span = $name, message = "JSON keys must use camelCase.", severity = "warn" )}{ "userName": "alice", "user_name": "bob", "UserAge": 30, "email": "a@b.com"}user_name (snake_case) and UserAge (PascalCase) are matched by the regex alternatives. userName and email are valid camelCase and are not matched.
Try this example in the playground
Advanced patterns
Section titled “Advanced patterns”Ban logging in specific lines
Section titled “Ban logging in specific lines”To apply a rule to only part of a file, filter its matches by position with range(). This rule bans console.log() calls that lie entirely within lines 2 and 3, and skips the calls before and after that range. A call that spans several lines matches only if the whole call is inside the range.
`console.log($...)` as $call where { $call <: range(start_line=2, end_line=3), register_diagnostic( span = $call, message = "Remove logging from this region.", severity = "warn" )}console.log("before");console.log("selected");console.log("also selected");console.log("after");Lines 2 and 3 are matched. Lines 1 and 4 are outside the range.
Try this example in the playground
Combine several rules in one file
Section titled “Combine several rules in one file”A top-level or can also group several independent rules in a single .grit file. Each arm has its own pattern, conditions, and diagnostic. Put a where clause inside each arm to give each rule its own severity and message.
This plugin combines three checks for debugging code:
or { `debugger` as $match where { register_diagnostic( span = $match, message = "Remove `debugger` statements before committing." ) }, `alert($...)` as $match where { register_diagnostic( span = $match, message = "Remove `alert()` calls before committing." ) }, `console.$method($...)` as $match where { $method <: or { `log`, `debug`, `trace` }, register_diagnostic( span = $match, message = "Remove debug logging before committing.", severity = "warn" ) }}debugger;alert("test");console.log("debug info");console.error("real error");console.debug("trace");Lines 1, 2, 3, and 5 are matched by different arms of the or. Line 4 (console.error) is not in the log, debug, trace list and is not matched.
Try this example in the playground
Find node names
Section titled “Find node names”Several examples above match Biome’s syntax nodes, such as JsConditionalExpression or TsAnyType, and start with the engine biome(1.0) directive. To find the right node name for the code you want to match, see Find node names in the GritQL reference.
© 2023-present Biome developers and contributors.