CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-lit-html

HTML templates literals in JavaScript that enable efficient, expressive HTML templating with incremental DOM updates

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

lit-html

lit-html is an efficient, expressive, and extensible HTML templating library for JavaScript that enables developers to write HTML templates using template literals with embedded JavaScript expressions. It provides a powerful template tag html for creating templates and a render function for efficiently rendering these templates to the DOM with automatic updates when values change.

Package Information

  • Package Name: lit-html
  • Package Type: npm
  • Language: TypeScript/JavaScript
  • Installation: npm install lit-html

Core Imports

import { html, render } from 'lit-html';

For specific features:

import { html, render, svg, mathml, nothing, noChange } from 'lit-html';
import { directive, Directive } from 'lit-html/directive.js';
import { AsyncDirective } from 'lit-html/async-directive.js';
import { repeat } from 'lit-html/directives/repeat.js';
import { classMap } from 'lit-html/directives/class-map.js';
import { isServer } from 'lit-html/is-server.js';

Basic Usage

import { html, render } from 'lit-html';

// Create a template
const myTemplate = (name: string) => html`<h1>Hello, ${name}!</h1>`;

// Render to the DOM
render(myTemplate('World'), document.body);

// Dynamic updates - only changed parts re-render
render(myTemplate('Universe'), document.body);

Architecture

lit-html is built around several key concepts:

  • Template Literals: JavaScript template literals with embedded expressions
  • Incremental DOM: Efficient updates by patching only changed parts
  • Template Results: Lazy evaluation - templates describe DOM structure without creating it
  • Parts System: Internal representation of dynamic portions of templates
  • Directive System: Extensible system for custom template behaviors
  • Static Templates: Optimization for templates with static parts
  • Server-Side Rendering: Support for rendering templates on the server

Capabilities

Core Template System

Essential template creation and rendering functionality for building dynamic HTML interfaces.

function html(strings: TemplateStringsArray, ...values: unknown[]): TemplateResult;
function svg(strings: TemplateStringsArray, ...values: unknown[]): SVGTemplateResult;
function mathml(strings: TemplateStringsArray, ...values: unknown[]): MathMLTemplateResult;
function render(
  value: unknown,
  container: HTMLElement | DocumentFragment,
  options?: RenderOptions
): RootPart;

Core Templates

Built-in Directives

Comprehensive collection of directives for common templating patterns including conditional rendering, lists, styling, and performance optimization.

// Conditional rendering
function when<C, T, F = undefined>(
  condition: C,
  trueCase: (c: Exclude<C, Falsy>) => T,
  falseCase?: (c: Extract<C, Falsy>) => F
): C extends Falsy ? F : T;

// List rendering with efficient updates
function repeat<T>(
  items: Iterable<T>,
  keyFnOrTemplate: KeyFn<T> | ItemTemplate<T>,
  template?: ItemTemplate<T>
): DirectiveResult;

// Dynamic CSS classes
function classMap(classInfo: ClassInfo): DirectiveResult;

// Dynamic inline styles
function styleMap(styleInfo: StyleInfo): DirectiveResult;

Built-in Directives

Custom Directive System

Framework for creating custom directives to extend template functionality with lifecycle management and state.

function directive<C extends DirectiveClass>(c: C): (...values: DirectiveParameters<InstanceType<C>>) => DirectiveResult<C>;

abstract class Directive {
  abstract render(...props: Array<unknown>): unknown;
  update(part: Part, props: Array<unknown>): unknown;
}

abstract class AsyncDirective extends Directive {
  isConnected: boolean;
  setValue(value: unknown): void;
  protected disconnected(): void;
  protected reconnected(): void;
}

Custom Directives

Static Templates

Optimization system for templates with static parts that don't change, enabling better performance and smaller bundle sizes.

function literal(strings: TemplateStringsArray, ...values: unknown[]): StaticValue;
function unsafeStatic(value: string): StaticValue;

// Enhanced template functions with static support
function html(strings: TemplateStringsArray, ...values: unknown[]): TemplateResult;
function svg(strings: TemplateStringsArray, ...values: unknown[]): TemplateResult;
function mathml(strings: TemplateStringsArray, ...values: unknown[]): TemplateResult;

Static Templates

Polyfill Support

Platform support utilities for environments that need polyfills for web components functionality.

/**
 * Installs platform polyfills to support lit-html in older browsers.
 * Call this once before using lit-html in environments that need polyfills.
 */
function installPolyfills(): void;

/**
 * Polyfill support interface for customizing template creation.
 */
interface PolyfillSupport {
  (template: typeof Template, childPart: typeof ChildPart): void;
}

Debug and Development APIs

Development and debugging utilities available in dev mode builds. These APIs are not available in production builds.

/**
 * Unstable debug APIs for development tooling and visualization.
 * Only available when DEV_MODE is true and window.emitLitDebugLogEvents is set.
 */
namespace LitUnstable {
  namespace DebugLog {
    interface Entry {
      kind: 'template prep' | 'begin render' | 'end render' | 'template instantiated' 
           | 'template updating' | 'commit text' | 'commit node' | 'commit attribute'
           | 'commit property' | 'commit boolean attribute' | 'commit event listener';
      // Additional properties vary by entry type
    }
  }
}

/**
 * Global flag to enable debug event emission in development mode.
 * Set this before using lit-html to receive 'lit-debug' events on window.
 */
declare global {
  interface Window {
    emitLitDebugLogEvents?: boolean;
  }
}

Usage Examples:

// Enable debug logging (development only)
if (process.env.NODE_ENV === 'development') {
  window.emitLitDebugLogEvents = true;
  
  // Listen for debug events
  window.addEventListener('lit-debug', (event) => {
    console.log('Lit debug event:', event.detail);
    
    switch (event.detail.kind) {
      case 'begin render':
        console.log('Starting render with value:', event.detail.value);
        break;
      case 'template prep':
        console.log('Template prepared:', event.detail.template);
        break;
      case 'commit text':
        console.log('Text committed:', event.detail.value);
        break;
    }
  });
}

Core Types

interface TemplateResult<T extends ResultType = ResultType> {
  readonly strings: TemplateStringsArray;
  readonly values: unknown[];
}

type HTMLTemplateResult = TemplateResult<typeof HTML_RESULT>;
type SVGTemplateResult = TemplateResult<typeof SVG_RESULT>;
type MathMLTemplateResult = TemplateResult<typeof MATHML_RESULT>;

interface RenderOptions {
  host?: object;
  renderBefore?: ChildNode | null;
  creationScope?: { importNode(node: Node, deep?: boolean): Node };
  isConnected?: boolean;
}

interface RootPart extends ChildPart {
  setConnected(isConnected: boolean): void;
}

// Sentinel values
const nothing: unique symbol;
const noChange: unique symbol;
Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/lit-html@3.3.x
Publish Source
CLI
Badge
tessl/npm-lit-html badge