Skip to content

About Lit 2.0

Kevin Schaaf edited this page Apr 2, 2021 · 7 revisions

Lit 2.0 is a new major version of the LitElement and lit-html libraries for writing fast, lightweight, close-to-the-platform web components. Lit combines the lit-html templating library and LitElement custom element base class into one easy-to-use library, with a single name, even more modern core, and unified documentation.

Lit's mission is to provide component authors with exactly what they need to make durable, interoperable components that work anywhere HTML does, including within any framework.

Lit 2.0's journey started with issues brainstorming what we could change in major versions of lit-html and lit-element:

Lit 2.0 includes new and updated versions of several libraries:

  • lit 2.0: The new primary home of Lit which includes everything from lit-html and lit-element
  • lit-html 2.0: Improvements in perf and code size. SSR-ready. New features and new dev mode build.
  • lit-element 3.0: Improvements in perf and code size. SSR-ready. New features and new dev mode build.
  • @lit/reactive-element: The new home and name of LitElement's underlying base class (which used to be UpdatingElement). We've broken this library out so that it's easier for other rendering libraries to use the core reactive properties and reactive lifecycle of LitElement. Also includes the new Reactive Controller interface.
  • @lit/localize: A library and command-line tool for localizing web applications built using Lit.
  • @lit/localize-tools: Localization tooling for use with @lit/localize.
  • @lit/virtualizer: List virtualization

It also includes a new "labs" org where we we're publishing new features or libraries we're incubating while collecting feedback:

  • @lit-labs/ssr: A server package for rendering Lit templates and components on the server.
  • @lit-labs/ssr-cient: A set of client-side support modules for rendering Lit components and templates on the server using @lit-labs/ssr.
  • @lit-labs/react: A React component wrapper for web components.
  • @lit-labs/task: A controller for Lit that renders asynchronous tasks.
  • @lit-labs/scoped-registry-mixin: A mixin for LitElement that integrates with the speculative Scoped CustomElementRegistry polyfill.

Backwards compatibility

Even though this is a new major version and contains some breaking changes, we have tried to make the breaking changes as small as possible, and to add new features to the current versions to enable forward-compatibility and ease migration.

For most users the new versions will be drop-in replacements. The main lit-html and LitElement APIs have not changed. The most significant breaking change is in the lit-html directive definition API, which we changed to make easier to use and more SSR-friendly. We've added most of this API to lit-html 1.4.0.

See the Lit 2.0 Upgrade Guide for a step-by-step guide to upgrading existing code to Lit 2.0 and a full list of minor breaking changes.

Motivation

lit-html and LitElement have been stable and their usage has been growing healthily since their initial release 3 years ago. There were no major problems with the current versions that needed fixing, but we saw some opportunities to make improvements with breaking changes. A lot of these were discovered when developing SSR for Lit.

  • lit-html allowed for an extreme amount of customization - you could completely change the syntax and create dynamic parts anywhere. This customization was never well supported in tools though (linters, etc) and wouldn't be supported in SSR. We simplified the codebase and improved perf by removing it.
  • Directives were hard to write and make compatible with SSR.
  • Browsers have fixed bugs. In particular working around one Safari template literal bug had a perf impact for all browsers.
  • Modern browsers had to pay for IE support. We wanted to be able to optimize better for modern browsers.

New Features

lit

A new package, named simply lit, is now the preferred entrypoint to both lit-html and LitElement. Most users should only need to install the lit package to start writing components or templates with Lit.

All packages: development builds

All the Lit npm packages now publish production and development builds. The production builds are highly minified, while the development builds are not and include additional error detection and warnings.

The production build is the package default, and development builds are published using npm-standard conditional exports. Most tools like bundlers and dev servers can now select an export condition, like 'development', to use across all packages in a project.

lit-html

Element expressions

Element expressions are bound to elements, similar to an attribute expression, but they don't require an attribute name. Currently, there's no built-in support for passing values to an element expression, so only directives can appear in them.

html`<div ${animate()}></div>`

Class-based directive API

The new class-based directive API makes it easier to write stateful directives that are compatible with SSR. lit-html now takes care of creating a directive instance and associating it with a template part. Storing state is as simple as using a class field.

The new directive API has an SSR-compatible render() callback which returns lit-html values like template results, and a client-side only update() callback that can manipulate DOM directly.

Async Directives

A long-requested feature of directives has been some way to do work when the directive or DOM it's attached to is removed from the document. AsyncDirective is a new base class that enables developers to write disconnected() and reconnected() callbacks.

This is great for use cases like directives that subscribe to external resources like RxJS observables.

Refs

With element expressions we also have a nice place to put a new ref() directive. ref() is a way to set up a reference to an element that's fulfilled once the element is actually rendered.

Refs can be forwarded to other components, or stored locally and used later in places like event handlers.

  private divRef = createRef();
  render() { return html`<div ${ref(this.divRef)}></div>`; }
  onClick() { console.log(divRef.value); }

Static Expressions

Static expressions allow developers to parameterize the static parts of templates. Usually bindings can only appear in a few position: attribute values, children/text, and elements, and the template has to be well-formed with balanced tags.

Static expressions are evaluated before normal template processing, so they can contain any HTML. The requirements for normal dynamic expressions apply after the static expressions have been evaluated. In effect static expressions let developers create new templates at runtime. You can bind to element tag names, attribute names, insert header and footer fragments that are individually unbalanced, but balanced together, and more.

Compiled template support

We've added a new template result type that is intended to be used by compilers and other template systems. This result must be prepared outside of lit-html - like at build time - and lit-html skips template preparation. We plan to publish tools to allow pre-compiling Lit templates to take advantage of this in the future.

Multiple expressions in unquoted attributes

lit-html 2.0 has a more accurate HTML syntax scanner and lifts the restriction that multiple attribute bindings in a single attribute value be quoted. So you can do:

html`<div foo=${a}${b}></div>`

LitElement

Reactive Controllers

Reactive controllers are a new way for helper objects to hook into a component's reactive update lifecycle.

ReactiveElement

Shadow root & styles support

LitElement's code for creating a shadow root, static styles support, the css template tag have been moved into the ReactiveElement base class. This means that LitElement is now entirely focused on using lit-html to render and all other functionality has been moved into ReactiveElement.

If you're building a component with purely imperative rendering or using another template system like Preact, you can extend from ReactiveElement instead of LitElement.

Shadow root rendering can still be opted-out by overriding createRenderRoot() to return this.

static shadowRootOptions

If you need to customize the options passed to attachShadow() you can now specify them in static shadowRootOptions rather than overriding createRenderRoot().

static finalizeStyles()

Classes can override static finalizeStyles() in order to integrate user styles with styles from another source such as a theming system.

Labs

In order to try new ideas and get feedback on them before they are production-ready, we have created a new npm organization called @lit-labs to host experimental packages.

@lit-labs/ssr and @lit-labs/ssr-client

As mentioned above, a large motivator for the changes in Lit 2.0 were driven by a desire to support server-side rendering. The @lit-labs/ssr package includes a node implementation for server-rendering of Lit components and templates. It takes advantage of Lit's declarative tagged string-based templating to avoid needing a full DOM shim on the server, and allows incremental streaming of HTML and efficient hydration and reuse of server-rendered DOM on the client. It takes advantage of declarative shadow root, a new feature that is shipping in Chrome 90, with a polyfill for other browsers.

Although the SSR package will initially remain in labs at Lit 2.0's launch, we've developed and tested the SSR support alongside the new libraries, ensuring that components written with Lit 2.0 today can take advantage of SSR support in the future.

The SSR package still needs some fine tuning, refinement of the end-user server APIs, and a full documentation suite before it's ready for general consumption, but motivated users can kick the tires on it today and provide feedback.

@lit-labs/react

@lit-labs/react is a package of utilities to help use web components in React.

createComponent()

createComponent() creates a React component definition from a web component class. It allows JSX to set properties (not just attributes) on a web component, and sets up event listener properties, since React has no way of adding event listeners generally via JSX.

useController()

useController() wraps a reactive controller as a React hook, allowing you to write cross-framework, reusable units of state and logic with reactive controllers.

@lit-labs/task

The Task reactive controller lets you easily define an asynchronous task as a function, and triggers host element updates as the task completes or fails. It includes a template helper to render different templates depending on the task state.

@lit-labs/scoped-registry-host

The ScopedRegistryHost mixin gives LitElement support for the scoped custom element registry proposal, which allows web components to have their own isolated registry of custom element definitions.