What is lit-html?
The lit-html npm package is a simple, modern, and efficient library for creating and managing HTML templates with JavaScript. It uses JavaScript template literals with embedded HTML markup to render dynamic content in web applications. The library is designed to be lightweight and fast, with a focus on minimizing the amount of work needed to update the DOM when the application state changes.
What are lit-html's main functionalities?
Dynamic Template Binding
lit-html allows you to bind data dynamically to your HTML templates using JavaScript expressions within template literals. The example code shows how you can insert a variable 'name' into a paragraph element.
`<p>Hello, ${name}!</p>`
Conditional Rendering
You can use JavaScript ternary operators to conditionally render parts of your template. This example demonstrates rendering a different paragraph element based on the truthiness of a 'condition' variable.
`${condition ? html`<p>True</p>` : html`<p>False</p>`}`
Repeating Templates
lit-html provides a straightforward way to render lists or repeat templates by using standard JavaScript array methods like 'map'. In this code, 'items' is an array that is being mapped to a list of 'li' elements.
`${items.map(item => html`<li>${item}</li>`)}`
Event Handling
Event handling in lit-html is done by prefixing the event name with an '@' symbol and assigning a handler function. The example shows a button element that calls the 'handleClick' function when clicked.
`<button @click=${handleClick}>Click me</button>`
Composability
lit-html templates can be composed together to build complex UIs. This example demonstrates how you can combine different template parts, like 'headerTemplate' and 'footerTemplate', to create a complete layout.
`${headerTemplate} ${footerTemplate}`
Other packages similar to lit-html
react
React is a popular library for building user interfaces. It also uses a component-based model and JSX for templating, which is similar to lit-html's use of template literals. However, React has a larger ecosystem and provides more features out of the box, such as state management and lifecycle methods.
vue
Vue is another popular framework that offers a reactive and composable data model. It uses an HTML-based template syntax that allows you to declaratively bind the rendered DOM to the underlying component state. Vue's approach is more similar to traditional HTML and less JavaScript-centric compared to lit-html.
svelte
Svelte is a compiler-based framework that shifts much of the work to compile time, resulting in smaller runtime size and potentially better performance. Like lit-html, Svelte uses a templating syntax that is close to standard HTML but with additional features for reactivity and state management.
lit-html 2.0 Pre-release
Efficient, Expressive, Extensible HTML templates in JavaScript
🚨 About this pre-release
This is a major version pre-release of lit-html 2.0. See issue
#1182 for the full list of changes
planned/considered for this release.
This pre-release is not yet feature complete or API stable. Please note the
breaking changes, known issues, and limitations below, and use at your risk
until the stable release is available. Issues are welcome
for unexpected changes not noted below or in the changelog.
🚨 Breaking changes
While lit-html
2.0 is intended to be a backward-compatible change for the
majority of 1.x users, please be aware of the following notable breaking
changes:
- New
directive
and Part
API (see below for migration info) render()
no longer clears its container on first render- Custom
templateFactory
, TemplateProcessor
, and custom tag functions are no
longer supported - The
polyfill-support.js
file must be loaded when using the webcomponents
polyfills
See the full changelog for more details on
these and other minor breaking changes.
🚨 Migrating directives
While the API for using directives should be 100% backward-compatible with
1.x, there is a breaking change to how custom directives are authored. The API
change improves ergonomics around making stateful directives while providing a
clear pattern for SSR-compatible directives: only render
will be called on the
server, while update
will not be.
Expand here for details on migrating directives.
Overview of directive API changes
| 1.x API | 2.0 API |
---|
Code idiom for directive | function that takes directive arguments, and returns function that takes part and returns value | class with update & render methods which accept directive arguments |
Where to do declarative rendering | pass value to part.setValue() | return value from render() method |
Where to do imperative DOM/part manipulation | directive function | update() method |
Where state is stored between renders | WeakMap keyed on part | class instance fields |
How part validation is done | instanceof check on part in every render | part.type check in constructor |
Example directive migration
Below is an example of a lit-html 1.x directive, and how to migrate it to the
new API:
1.x Directive API:
import {directive, NodePart, html} from 'lit-html';
const previousState = new WeakMap();
export const renderCounter = directive((initialValue) => (part) => {
if (!(part instanceof NodePart)) {
throw new Error('renderCounter only supports NodePart');
}
let value = previousState.get(part);
if (previous === undefined) {
value = initialValue;
} else {
value++;
}
previousState.set(part, value);
part.setValue(html`<p>${value}</p>`);
});
2.0 Directive API:
import {html} from 'lit-html';
import {directive, Directive, PartType} from 'lit-html/directive.js';
export const renderCounter = directive(
class extends Directive {
value = undefined;
constructor(partInfo: PartInfo, index?: number) {
super(partInfo, index);
if (partInfo.type !== PartType.CHILD) {
throw new Error('renderCounter only supports child expressions');
}
}
update(part, [initialValue]) {
}
render(initialValue) {
if (this.value === undefined) {
this.value = initialValue;
} else {
this.value++;
}
return html`<p>${this.value}</p>`;
}
}
);
lit-html
Overview
lit-html
lets you write HTML templates in JavaScript with template literals.
lit-html templates are plain JavaScript and combine the familiarity of writing HTML with the power of JavaScript. lit-html takes care of efficiently rendering templates to DOM, including efficiently updating the DOM with new values.
import {html, render} from 'lit-html';
const helloTemplate = (name) => html`<div>Hello ${name}!</div>`;
render(helloTemplate('Steve'), document.body);
render(helloTemplate('Kevin'), document.body);
lit-html
provides two main exports:
html
: A JavaScript template tag used to produce a TemplateResult
, which is a container for a template, and the values that should populate the template.render()
: A function that renders a TemplateResult
to a DOM container, such as an element or shadow root.
Installation
$ npm install lit-html
Development mode
lit-html includes a development mode which adds additional checks that are
reported in the console.
To enable development mode, add the development
exports condition to your node
resolve configuration.
@web/dev-server
{
nodeResolve: {
exportConditions: ['development'],
}
}
Rollup
{
plugins: [
nodeResolve({
exportConditions: ['development'],
}),
],
}
Webpack
NOTE: Requires Webpack v5
{
resolve: {
conditionNames: ['development'],
}
}
Contributing
Please see CONTRIBUTING.md.