Skip to content

Staticview ESLint Plugin

@staticview/eslint-plugin checks web components built with @staticview/core. It catches code that breaks the build, the generated types, or the target browsers.

Installation

Terminal window
npm install --save-dev @staticview/eslint-plugin typescript-eslint

It needs ESLint 9.22 or later.

Setup

Extend recommended for your component scripts, and scope files to the component files only, since other files give false reports. The recommended rules need type information, which the parser of typescript-eslint gives with parserOptions.projectService.

import sv from "@staticview/eslint-plugin";
import { defineConfig } from "eslint/config";
import tsEslint from "typescript-eslint";
export default defineConfig([
{
files: ["src/components/**/*.ts"],
extends: [sv.configs.recommended],
languageOptions: { parser: tsEslint.parser, parserOptions: { projectService: true } },
rules: {
"sv/compat-dom": "warn", // Override any rule after `recommended`
},
},
]);

The rules for stylesheets and templates need blocks of their own, since they run on the languages of @eslint/css and @html-eslint/eslint-plugin. compat-partial and compat-tag-note run on all three languages:

import css from "@eslint/css";
import html from "@html-eslint/eslint-plugin";
const browserSupportRules = {
"sv/compat-partial": "warn",
"sv/compat-tag-note": "warn",
};
export default defineConfig([
{
files: ["src/components/**/*.ts"],
extends: [sv.configs.recommended],
languageOptions: { parser: tsEslint.parser, parserOptions: { projectService: true } },
rules: browserSupportRules,
},
{
files: ["src/components/**/*.css"],
plugins: { css, sv },
language: "css/css",
languageOptions: { tolerant: true },
rules: { "sv/check-stylesheet-documentation": "error", "sv/compat-css": "error", ...browserSupportRules },
},
{
files: ["src/components/**/*.html"],
plugins: { html, sv },
language: "html/html",
rules: { "sv/check-template-documentation": "error", "sv/compat-html": "error", ...browserSupportRules },
},
]);

Rules

✅ is in recommended. 🔧 is fixable with --fix.

Rule Checks
check-macros Calls to $inline and $shadow ✅
no-import-export-value Value imports and exports ✅ 🔧
no-dynamic-css-class-name Class names the build cannot rename ✅
no-dynamic-css-variable CSS variable names the build cannot rename ✅
custom-element-name The tag name in _componentName ✅
export-component-types The [ComponentClassName]Types export ✅
check-public-api-documentation-and-types Docs and types of the public API ✅
check-template-documentation Docs of the slots and parts in a template
check-stylesheet-documentation Docs of the CSS variables in a stylesheet
explicit-class-member-types Type annotations on class properties ✅ 🔧
arrow-public-methods Public methods as readonly arrow functions ✅ 🔧
observed-attributes The shape of observedAttributes ✅
native-property-name The casing of native property names ✅
no-uninitialized-optional-property Optional properties with no value ✅ 🔧
no-true-default-attribute Boolean attributes that default to true ✅
no-invalid-event-name Event names ✅
no-this-element-selector Child queries on the host ✅
prefer-owner-document The global document in instance code ✅ 🔧
no-internals-states-has has() on ElementInternals.states ✅
compat-dom Script features a target browser lacks ✅
compat-css CSS features a target browser lacks
compat-html HTML features a target browser lacks
compat-partial Features a target browser supports only partly
compat-tag-note Browser support tags
consistent-class-member-order The order of class members ✅ 🔧
prefer-static-private-methods Private methods that do not use this ✅ 🔧
sort-object-and-type-keys Quoted keys mixed with unquoted keys 🔧
no-restricted-phrases Phrases in comments and Markdown

check-macros

The file that $inline or $shadow names must exist. $inline takes a string literal, and $shadow takes an object literal with string literals in htmlFile and cssFile. $shadow takes htmlFile or htmlString, not both, and the same goes for cssFile and cssString.

no-import-export-value

Since the build wraps each component in an IIFE to run it from a classic <script> tag, an imported or exported value breaks inside that wrapper. import type and export type stay allowed.

no-dynamic-css-class-name

The build renames classes, and it cannot follow a name built at runtime, like with a template literal. It does not rename the classes in an innerHTML string either, and the rule reports every class there that ignorePrefix does not cover.

A selector read from ._componentName, .localName, or .tagName passes, and calls on document or on an ownerDocument are skipped.

A disable comment for this rule above a line also makes the build leave its class names as they are, with no warning. Keep ignorePrefix equal to the minifyCssClassesIgnorePrefix of the build.

Option Default Effect
ignorePrefix ["_"] Class name prefixes to skip

no-dynamic-css-variable

The build renames CSS variables with the same limit as class names, and a disable comment for this rule above a line also makes the build leave them as they are. Keep ignorePrefix equal to the minifyCssVariablesIgnorePrefix of the build.

Option Default Effect
ignorePrefix ["sv-", "_"] Variable name prefixes to skip, without --

custom-element-name

The static _componentName must be a readonly string literal with at least one hyphen. It holds only lowercase letters, digits, and hyphens, starts with a letter, does not start with xml, and is not a reserved name, like font-face. Mark a base class abstract to skip it.

export-component-types

Each component file exports a [ComponentClassName]Types type, which the framework types are generated from. Mark a base class abstract to skip it.

export type AccordionTypes = SV.WComponent<typeof Accordion>;
class Accordion extends HTMLElement implements SV.IWebComponent {}

check-public-api-documentation-and-types

The rule runs the analyzer that generates the docs and the framework types, and reports:

  • a JSDoc tag that changes nothing, because the analyzer infers the same value,
  • a public item with no description,
  • a public item that is not a key of the exported [ComponentClassName]Types,
  • an attribute in the types that the docs do not list,
  • an @extends path that does not exist or does not parse.

Attributes are checked against the Attributes key, properties and methods against members and OverriddenProps, and events against Events. An item that HTMLElement already has with the same type, like hidden, needs no type of its own.

Option Default Effect
shouldReportRedundantTags true Report tags that change nothing
missingDescriptionItemCategories All categories Categories to check for a description
missingTypeItemCategories All categories Categories to check for a type

The categories are "attributes", "properties", "methods", "events", and "cssStates" for descriptions only. An empty list turns that check off.

check-template-documentation

The rule runs on the component HTML files, and reports:

  • a slot or part with no description in a comment above it,
  • a @slot or @cssPart tag that repeats the name of the element below it.

Describe slots and parts in the template, not in the class JSDoc, since the rule reads only the template. Put <!-- @ignore --> above an element to leave it out of the docs.

<!-- @slot - The content of the header. -->
<slot name="header"></slot>

check-stylesheet-documentation

The rule runs on the component CSS files, and reports:

  • a CSS variable with no description in a comment above it,
  • a @cssVar tag that repeats the name of the declaration below it.

The rule reads the variables declared in the top-level :host rule and in the top-level root rule, which is .root, .<name>-root, .<name>_root, or .<camelName>Root. Describe CSS variables in the stylesheet, not in the class JSDoc, since the rule reads only the stylesheet.

:host {
/* The color of the track. */
--sv-slider-track-clr: var(--sv-clr-surface);
}

explicit-class-member-types

The analyzer reads the type from an annotation directly, with no inference. The rule checks properties and getters, and --fix writes the inferred type.

Option Default Effect
shouldCheckStaticMembers false Check static properties
shouldCheckInstanceMembers true Check instance properties
shouldCheckPrivateMembers false Check # and _ members
shouldCheckReadonlyFunctionMembers true Check readonly members that hold a function

arrow-public-methods

The framework types need a readonly arrow function to tell a method apart from an assignable property.

Option Default Effect
ignored Lifecycle callbacks and native DOM members Method names to skip

A list in ignored replaces the built-in one.

observed-attributes

observedAttributes must be a public static array with as const. Without as const, the types lose the name of each attribute.

native-property-name

A public property uses the casing of the native DOM property with the same name, like readOnly and tabIndex, because frameworks set the native name. Angular turns a [readonly] binding into el.readOnly = value, and a readonly property never gets the value.

no-uninitialized-optional-property

Since the build removes a class field with no initializer, React 19 sets an attribute in place of the missing property, and the component never gets the value. Give the field an initializer, like duration: number | undefined = undefined, or assign it in the constructor.

no-true-default-attribute

A property of an observed attribute must not default to true, since markup cannot set a boolean attribute to false and has no way to turn it off.

no-invalid-event-name

The name of each new CustomEvent() has only lowercase letters and is not a native DOM event name, like change. It does not start with on either, since frameworks read that prefix as an event binding, like onClick.

Option Default Effect
ignored [] Event names to skip
extend Native DOM events Names to report

A list in extend replaces the built-in one.

no-this-element-selector

Since the children may not exist yet when this.querySelector() runs, use slots and the slotchange event instead. The rule also reports other child reads on the host, like this.children.

Option Default Effect
ignored [] Member names to skip
extend Child queries Member names to report

A list in extend replaces the built-in one.

prefer-owner-document

An element can move to another document, like the one of an iframe, and this.ownerDocument is always the one that holds it now.

A static member gets no fix, and it needs a Document parameter or an element argument to read ownerDocument from.

no-internals-states-has

Since WebKit can garbage collect ElementInternals.states while the element lives, has() on it can return false for a state that is set. Keep the set in a field, like readonly #states = this.#internals.states, and call has() on the field. add() and delete() are safe to call in place.

compat-dom

The rule reads members, globals, constructors, method arguments, addEventListener events, and the CSS properties a style object sets. A build-time call, like $shadow, reads its keys from the keysByFunction table of the config.

compat-css

The rule reads properties, values, functions, units, selectors, at-rules, and media and container features.

Autoprefixer runs for the targets first, and a prefixed twin counts its own support. A lone vendor-prefixed spelling counts as an enhancement.

compat-html

The rule reads elements, attributes, and embedded SVG and MathML. It skips data-*, aria-*, role, and xmlns, and a nested custom element counts only for its global attributes.

Since HTML allows no comment in a start tag, put the tag above the element and name each attribute key it covers.

compat-partial

The rule reports a required feature that a target browser supports only partly. A feature that a target lacks completely is left to the rule of its language.

compat-tag-note

The rule reports a tag with no key, no note, or a key that matches no browser-compat-data key.

/* @enhancement Scrollbars keep the default look. */ /* No key */
/* @enhancement css.properties.scrollbar-width: */ /* No note */
/* @enhancement css.properties.scrollbar-wdth: Scrollbars keep the default look. */ /* Unknown key */
/* @enhancement css.properties.scrollbar-width: Scrollbars keep the default look. */ /* Fine */

consistent-class-member-order

The rule keeps the members of a component class in one order. A _ prefix counts as private, like #. A getter, its setter, and the private field of the same name stay together, and protected members keep their place.

Option Default Effect
membersOrder See below Order of member groups
lifecycleHooksOrder See below Order of lifecycle callbacks
shouldGroupAccessors true Keep the accessors of one name together
accessorsOrder ["getter", "setter", "field"] Order inside an accessor group
shouldReadonlyBeFirst true readonly members first, null to skip
shouldUnderscorePrivateBeFirst true _ before # members, null to skip
excludedMemberNames [] Members to leave in place

The default member order is "private-static-fields", "private-instance-fields", "public-static-fields", "public-instance-fields", "constructor", "lifecycle-hooks", "public-static-methods", "public-instance-methods", "private-static-methods", and "private-instance-methods".

The default lifecycle order is attachShadow, connectedCallback, connectedMoveCallback, disconnectedCallback, attributeChangedCallback, adoptedCallback, checkValidity, reportValidity, setCustomValidity, focus, blur, formAssociatedCallback, formResetCallback, formStateRestoreCallback, and formDisabledCallback.

An order you set goes first, and the items it leaves out follow in the default order.

prefer-static-private-methods

A private method or arrow function property that does not use this should be static.

sort-object-and-type-keys

The rule keeps quoted keys, like "max-files", apart from unquoted keys in objects, interfaces, and type literals. The keys in each group keep their order, and a comment moves with its key.

Since sorting an object changes the order of Object.keys(), turn the rule off for an object whose code depends on that order.

Option Default Effect
quotedKeysPosition "last" "first" or "last"
shouldPartitionByBlankLine false Sort the keys between blank lines apart
shouldSortObjects true Check object literals
shouldSortTypes true Check interfaces and type literals

no-restricted-phrases

The rule reports each match of a regular expression in comments, and in the whole text of Markdown files. In a template, it also reads the comments of its <script> and <style> tags.

"sv/no-restricted-phrases": [
"error",
{ patterns: [{ pattern: String.raw`\bin order to\b`, message: 'Write "to".' }] },
],

Each pattern runs with the g and u flags. Without a message, the report asks for a rewrite without the match.

Browser Support

The compat rules read the config of @staticview/core/browser-support, whose README covers the config, the tags, and how a feature counts.

The rules use the nearest .browser-support.json to the linted file. settings.browserSupport in the ESLint config has the same shape and goes over the file. Without targets, the target is the browserslist config of the project.

settings: {
browserSupport: {
overrides: { "css.properties.scrollbar-width*": { tag: "enhancement", note: "Scrollbars keep the default look." } },
},
},

Since the browser support report reads only the root config files, leave settings.browserSupport unset to make the lint agree with it.

A comment tag tells how a feature counts, for its keys in the node below it and that node's subtree. Each report suggests one, and you write the note after the colon.

// @enhancement api.Element.beforematch_event: Find-in-page does not open a closed section.
this.#expanderEl.addEventListener("beforematch", () => this.open(true));
Tag Lint
None Reports a target that lacks it or has it partly
@partial Partial support counts
@limited, @enhancement, @unchecked Silent