diff --git a/.changeset/forty-bobcats-sneeze.md b/.changeset/forty-bobcats-sneeze.md new file mode 100644 index 0000000000..f1b63d0f27 --- /dev/null +++ b/.changeset/forty-bobcats-sneeze.md @@ -0,0 +1,7 @@ +--- +'lit-html': patch +--- + +In DEV_MODE, render a warning instead of rendering a template's host in the template. + +Most commonly this would happen when rendering `${this}` in a LitElement's template, which has the counterintuitive behavior of removing the element from the DOM, because when rendering the element's template we attach it into its own shadow root, which removes it from the DOM, causing it simply disappear. This is especially problematic with a fast HMR system. diff --git a/packages/lit-html/src/lit-html.ts b/packages/lit-html/src/lit-html.ts index aa065d7049..1b91526090 100644 --- a/packages/lit-html/src/lit-html.ts +++ b/packages/lit-html/src/lit-html.ts @@ -1455,6 +1455,21 @@ class ChildPart implements Disconnectable { } else if ((value as TemplateResult)['_$litType$'] !== undefined) { this._commitTemplateResult(value as TemplateResult); } else if ((value as Node).nodeType !== undefined) { + if (DEV_MODE && this.options?.host === value) { + this._commitText( + `[probable mistake: rendered a template's host in itself ` + + `(commonly caused by writing \${this} in a template]` + ); + console.warn( + `Attempted to render the template host`, + value, + `inside itself. This is almost always a mistake, and in dev mode `, + `we render some warning text. In production however, we'll `, + `render it, which will usually result in an error, and sometimes `, + `in the element disappearing from the DOM.` + ); + return; + } this._commitNode(value as Node); } else if (isIterable(value)) { this._commitIterable(value);