The foundation of Lit - base classes and template functions for creating reactive web components with declarative templates.
Base class for creating reactive web components with automatic change detection, lifecycle management, and template rendering.
/**
* Base class for creating reactive web components
* Extends ReactiveElement with template rendering capabilities
*/
class LitElement extends ReactiveElement {
/**
* Override to define the component's template
* Called automatically when properties change
*/
render(): TemplateResult | unknown;
/** Static styles applied to the component's shadow DOM */
static styles?: CSSResultGroup;
/** CSS custom properties and styles */
static shadowRootOptions?: ShadowRootInit;
}
/** Shadow root initialization options - part of DOM API */
interface ShadowRootInit {
mode: "open" | "closed";
delegatesFocus?: boolean;
}Usage Examples:
import { LitElement, html, css } from "lit";
class MyComponent extends LitElement {
static styles = css`
:host {
display: block;
padding: 16px;
}
`;
render() {
return html`<p>Hello from Lit!</p>`;
}
}Base reactive element class without templating - provides property observation and lifecycle management.
/**
* Base class for reactive elements with property observation
* Does not include template rendering (use LitElement for templates)
*/
class ReactiveElement extends HTMLElement {
/** Creates the element and initializes reactive properties */
constructor();
/** Called when element is added to DOM */
connectedCallback(): void;
/** Called when element is removed from DOM */
disconnectedCallback(): void;
/** Called when observed attributes change */
attributeChangedCallback(name: string, old: string | null, value: string | null): void;
/** Called when properties change, before update */
willUpdate(changedProperties: PropertyValues): void;
/** Called after DOM update completes */
updated(changedProperties: PropertyValues): void;
/** Promise that resolves when update cycle completes */
readonly updateComplete: Promise<boolean>;
/** Manually trigger an update cycle */
requestUpdate(name?: PropertyKey, oldValue?: unknown): void;
}Tagged template literal for creating HTML templates with expression interpolation.
/**
* Creates HTML template results from tagged template literals
* Supports expression interpolation and directive usage
*/
function html(
strings: TemplateStringsArray,
...values: unknown[]
): TemplateResult;Usage Examples:
import { html } from "lit";
// Basic template
const template = html`<h1>Hello World</h1>`;
// With expressions
const name = "Alice";
const greeting = html`<h1>Hello, ${name}!</h1>`;
// With directives
import { when } from "lit/directives/when.js";
const conditional = html`
${when(true, () => html`<p>Shown when true</p>`)}
`;Tagged template literal for creating SVG templates within HTML templates.
/**
* Creates SVG template results for use within HTML templates
* Automatically sets SVG namespace context
*/
function svg(
strings: TemplateStringsArray,
...values: unknown[]
): TemplateResult;Usage Examples:
import { html, svg } from "lit";
const icon = html`
<div class="icon">
${svg`
<svg width="24" height="24" viewBox="0 0 24 24">
<circle cx="12" cy="12" r="10" fill="blue"/>
</svg>
`}
</div>
`;Tagged template literal for creating MathML templates within HTML templates.
/**
* Creates MathML template results for mathematical expressions
* Automatically sets MathML namespace context
*/
function mathml(
strings: TemplateStringsArray,
...values: unknown[]
): TemplateResult;Creates CSS result objects for component styling with automatic deduplication.
/**
* Creates CSS results for component styling
* Automatically handles style deduplication and optimization
*/
function css(
strings: TemplateStringsArray,
...values: (string | number | CSSResult)[]
): CSSResult;Usage Examples:
import { LitElement, css } from "lit";
class StyledComponent extends LitElement {
static styles = css`
:host {
display: block;
color: var(--text-color, black);
}
.button {
padding: 8px 16px;
border: 1px solid currentColor;
background: transparent;
}
`;
}
// Composing styles
const baseStyles = css`
font-family: sans-serif;
`;
const componentStyles = css`
${baseStyles}
color: blue;
`;Creates CSS results from raw strings without processing. Use only with trusted CSS content.
/**
* Creates CSS results from raw CSS strings without template processing
* WARNING: Only use with trusted CSS content
*/
function unsafeCSS(css: string): CSSResult;Usage Examples:
import { LitElement, unsafeCSS } from "lit";
class DynamicStyledComponent extends LitElement {
@property() customCSS = "";
static styles = [
// Safe static CSS
css`
:host {
display: block;
}
`,
// Unsafe CSS from variable - only use with trusted content!
unsafeCSS(`
.dynamic {
color: red;
font-size: 16px;
}
`)
];
}
// Loading CSS from external source (ensure it's trusted!)
const externalCSS = await fetch('/trusted-styles.css').then(r => r.text());
const externalStyles = unsafeCSS(externalCSS);Applies styles to a shadow root, handling both CSSResult objects and native stylesheets.
/**
* Applies CSS styles to a shadow root or document
* Handles both CSSResult and CSSStyleSheet objects
*/
function adoptStyles(
renderRoot: ShadowRoot | Document,
styles: CSSResultGroup
): void;
type CSSResultGroup = CSSResult | CSSStyleSheet | Array<CSSResult | CSSStyleSheet>;Usage Examples:
import { adoptStyles, css } from "lit";
class ManualStyleComponent extends LitElement {
createRenderRoot() {
const root = this.attachShadow({ mode: 'open' });
// Manually adopt styles to shadow root
const customStyles = css`
:host {
background: lightblue;
padding: 20px;
}
`;
adoptStyles(root, [customStyles]);
return root;
}
}
// Adopting styles to document (useful for global styles)
const globalStyles = css`
body {
font-family: Arial, sans-serif;
}
`;
adoptStyles(document, globalStyles);Renders templates into DOM containers, typically used for rendering outside of components.
/**
* Renders templates into DOM containers
* Primarily for rendering outside of LitElement components
*/
function render(
value: unknown,
container: Element | DocumentFragment,
options?: RenderOptions
): void;
interface RenderOptions {
host?: object;
isConnected?: boolean;
creationScope?: Element | Document;
}Usage Examples:
import { html, render } from "lit";
// Render to existing DOM element
const template = html`<h1>Hello from Lit!</h1>`;
const container = document.getElementById("app");
render(template, container);
// With options
render(template, container, {
host: this,
isConnected: true
});Sentinel value indicating no change in directive results - prevents unnecessary DOM updates.
/**
* Sentinel value for directives to indicate no change
* Prevents DOM updates when directive value hasn't changed
*/
const noChange: unique symbol;Sentinel value for rendering nothing/empty content in templates.
/**
* Sentinel value for rendering empty content
* Removes content from DOM when used in templates
*/
const nothing: unique symbol;Flag indicating whether code is running in server environment for SSR support.
/**
* Boolean flag indicating server-side rendering environment
* True when running on server, false in browser
*/
const isServer: boolean;interface TemplateResult {
/** Type marker for HTML templates */
readonly _$litType$: 1;
strings: TemplateStringsArray;
values: readonly unknown[];
}
interface SVGTemplateResult extends TemplateResult {
/** Type marker for SVG templates */
readonly _$litType$: 2;
}
interface MathMLTemplateResult extends TemplateResult {
/** Type marker for MathML templates */
readonly _$litType$: 3;
}interface CSSResult {
/** CSS text content */
readonly cssText: string;
/** String representation of CSS */
toString(): string;
}
/** CSS result or array of CSS results */
type CSSResultGroup = CSSResult | CSSResult[];/** Map of property names to their previous values */
type PropertyValues<T = any> = Map<PropertyKey, unknown>;
/** Property key type (string, number, or symbol) - built into TypeScript */
type PropertyKey = string | number | symbol;
/** Configuration for reactive properties */
interface PropertyDeclaration<Type = unknown> {
/** Attribute name or false to disable attribute binding */
attribute?: boolean | string;
/** Type hint for property conversion */
type?: TypeHint;
/** Custom attribute converter */
converter?: AttributeConverter<Type>;
/** Whether to reflect property to attribute */
reflect?: boolean;
/** Custom change detection function */
hasChanged?(value: Type, oldValue: Type): boolean;
}
/** Attribute converter interface */
interface AttributeConverter<Type = unknown> {
fromAttribute?(value: string | null, type?: TypeHint): Type;
toAttribute?(value: Type, type?: TypeHint): unknown;
}
/** Type hints for property conversion */
type TypeHint = typeof String | typeof Number | typeof Boolean | typeof Array | typeof Object;