Web Components

webc/constructor-no-attributes

A custom element constructor never reads or adds attributes or children; do that in connectedCallback.

poważnastatycznefe-web-components

Dlaczego

An element made with document.createElement('acme-card') has no attributes and no children while its constructor runs, so reading them gives null. Adding them makes the creation fail: createElement throws, and so do frameworks that create elements this way. The element then works when written in HTML and breaks when a framework renders it.

Poprawka

In the constructor only call super(), set default state, attach the shadow root and add listeners. Read attributes in connectedCallback or attributeChangedCallback (list them in observedAttributes), and set a default role or state through ElementInternals (this.internals.role = 'button') instead of adding attributes to the host.

Przykłady

// bad
constructor() {
  super()
  this.setAttribute('role', 'button')
  this.label = this.getAttribute('label')
}
// good
constructor() {
  super()
  this.internals = this.attachInternals()
  this.internals.role = 'button'
  this.attachShadow({ mode: 'open' })
}
connectedCallback() { this.label = this.getAttribute('label') }

Źródła

Fakty

Identyfikator
webc/constructor-no-attributes
Waga
poważna
Sprawdzanie
statyczne sprawdzane w kodzie źródłowym przez audit
Dotyczy plików
jsx html
Uczy jej skill
fe-web-components Web components and Lit
Od wersji
0.1.0

Plik reguły na GitHubie

Przeczytaj w terminalu

npx github:dawidolko/frontend-skills explain webc/constructor-no-attributes