Configs2026年4月11日·1 分钟阅读

Lit — Simple Library for Fast Lightweight Web Components

Lit is a simple library for building fast, lightweight web components. Built by Google on top of the standard Web Components APIs, it provides reactive properties, scoped styles, and a declarative templating system in about 5KB.

AI
AI Open Source · Community
快速使用

先拿来用,再决定要不要深挖

这里应该同时让用户和 Agent 知道第一步该复制什么、安装什么、落到哪里。

npm i lit
// my-element.ts
import { LitElement, html, css } from "lit";
import { customElement, property } from "lit/decorators.js";

@customElement("my-counter")
export class MyCounter extends LitElement {
  static styles = css`
    button { padding: 0.5rem 1rem; font-size: 1rem; }
  `;

  @property({ type: Number }) count = 0;

  render() {
    return html`
      <button @click=${() => this.count++}>
        Clicked ${this.count} times
      </button>
    `;
  }
}
<my-counter count="5"></my-counter>
<script type="module" src="./my-element.js"></script>
介绍

Lit is a simple library for building fast, lightweight web components. Created at Google (successor to Polymer), Lit embraces the Web Components standards (Custom Elements, Shadow DOM, HTML templates) and adds just enough sugar: reactive properties, scoped styles, and efficient template re-renders. Used at Google, Adobe, Photoshop Web, and many design systems.

What Lit Does

  • LitElement — base class for reactive web components
  • html template tag — efficient tagged-template rendering
  • css template tag — scoped Shadow DOM styles
  • Reactive properties — declarative observed attributes
  • Lifecycle — connected/disconnected/updated callbacks
  • Directives — repeat, when, classMap, styleMap, ref
  • SSR — @lit-labs/ssr for server rendering
  • Interop — components work in React, Vue, Angular, plain HTML

Architecture

Lit compiles tagged templates into efficient render instructions (parts system), only updating the DOM bindings that changed. Components extend LitElement, get reactive property handling, and use Shadow DOM for style scoping. Output is plain web components — no framework lock-in.

Self-Hosting

Client library.

Key Features

  • ~5KB gzipped runtime
  • Standards-based (Web Components)
  • Reactive properties
  • Shadow DOM scoping
  • Efficient template re-renders
  • Framework interop (React/Vue/Angular)
  • SSR via @lit-labs/ssr
  • TypeScript decorators
  • Directive API for custom behavior

Comparison

Library Paradigm Standard Bundle Interop
Lit Web Components Yes ~5KB Universal
Stencil Web Components Yes Variable Universal
React Virtual DOM No 45KB React only
Svelte Compiled No Variable Own runtime
FAST Web Components Yes ~10KB Universal

常见问题 FAQ

Q: Web Components 值得用吗? A: 适合设计系统、跨团队复用、长期项目(不受框架更迭影响)。不适合需要 JSX/函数组件 DX 的快速迭代前端。

Q: 和 React 能一起用吗? A: 能。Lit 组件就是标准 HTMLElement,React 里 <my-counter count={5}></my-counter> 即可。事件要用 ref + addEventListener。

Q: SSR 支持? A: @lit-labs/ssr 提供 server-side render。还在实验阶段但已可用。

来源与致谢 Sources

讨论

登录后参与讨论。
还没有评论,来写第一条吧。

相关资产