Skip to content

Commit

Permalink
In DEV_MODE, render a warning instead of rendering a template's host …
Browse files Browse the repository at this point in the history
…in the template. (#3199)

* 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.

* Log a warning as well
  • Loading branch information
rictic committed Aug 5, 2022
1 parent 6361a4b commit 0725fdb
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
7 changes: 7 additions & 0 deletions .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.
15 changes: 15 additions & 0 deletions packages/lit-html/src/lit-html.ts
Expand Up @@ -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);
Expand Down

0 comments on commit 0725fdb

Please sign in to comment.