lit-element

repository·master·Indexed 26 days ago

https://github.com/lit/lit-element

A simple base class for creating fast, lightweight web components using lit-html. It manages properties, attributes, and declarative rendering into the Shadow DOM. Version 2.5.1 includes back-ported changes to ease migration to Lit 2.

Tokens
19.7K
Snippets
71
Records
108
Agent score
87%

What's inside lit-element

  1. Overview of LitElement

    master

    LitElement is a library for defining fast, lightweight Web Components. It allows you to express UI declaratively as a function of state using standard JavaScript in templates.

    Key features include:

    • Declarative UI: Elements update automatically when their properties change.
    • Performance: Uses lit-html to render only the dynamic parts of the UI, avoiding expensive DOM diffing.
    • Interoperability: Follows Web Components standards (Custom Elements and Shadow DOM), making components compatible with any framework (React, Vue, etc.) or plain HTML.
  2. Introduction to LitElement

    master
    LitElement is a lightweight base class used to create fast web components that are compatible with any web page or framework. It leverages lit-html to render content into the Shadow DOM and provides a built-in API for managing properties and attributes. Properties are observed by default, and the component triggers asynchronous updates whenever a property value changes.
  3. Understand the LitElement update lifecycle

    master

    The LitElement update lifecycle follows a specific sequence of methods and properties. Understanding this order is essential for implementing custom logic at the correct stage of an element's update cycle.

    Lifecycle Order:

    1. someProperty.hasChanged: Checks if a property value has actually changed.
    2. requestUpdate: Schedules an update.
    3. performUpdate: The actual update process begins.
    4. shouldUpdate: Determines if the update should proceed.
    5. update: Reflects properties to attributes and calls render.
    6. render: Generates the DOM via lit-html.
    7. firstUpdated: Called once after the initial DOM update.
    8. updated: Called after every DOM update.
    9. updateComplete: A Promise that resolves when the update cycle finishes.
  4. Transpile LitElement with TypeScript

    master

    If you are using TypeScript to write your LitElement components, it is recommended to target ES2017 with Node.js module resolution. This ensures your published code is in a standard format (ES2017) that most environments can consume without further transpilation.

    "compilerOptions": {
      "target": "es2017",
      "module": "es2015",
      "moduleResolution": "node",
      "lib": ["es2017", "dom"],
      "experimentalDecorators": true
    }
  5. Try LitElement in a live editor

    master
    You can experiment with LitElement using live-editable code samples in a browser-based environment (like StackBlitz) without performing a local installation. This allows you to build components, use them in web pages, and apply CSS styles immediately. Use the Preview button to see your changes in action.
  6. Add event listeners to templates using the @event annotation

    master

    You can add event listeners to elements within your lit-html templates using the @ prefix followed by the event name. The syntax @<event-name>=${this.handlerMethod} binds the specified event to a class method.

    For example, to listen for a click event on a button, use @click=${this.clickHandler}.

  7. Build LitElement components for production

    master

    To bundle LitElement components for production, use a bundler like Webpack or Rollup. A Rollup configuration can resolve dependencies and convert bare module specifiers into paths.

    Example rollup.config.js using rollup-plugin-node-resolve:

    import resolve from 'rollup-plugin-node-resolve';
    
    export default {
      // If using any exports from a symlinked project, uncomment the following:
      // preserveSymlinks: true,
      input: ['src/index.js'],
      output: {
        file: 'build/index.js',
        format: 'es',
        sourcemap: true
      },
      plugins: [
        resolve()
      ]
    };
  8. Use a LitElement component in your application

    master

    To use a third-party LitElement component, follow these steps:

    1. Install the component via npm:

      npm install some-package-name
    2. Import the component:

      • In a JavaScript module:
        import 'some-package-name';
      • In an HTML page using a module script:
        <script type="module">
        import './path-to/some-package-name/some-component.js';
        </script>
      • Or via a module script with a src attribute:
        <script type="module" src="./path-to/some-package-name/some-component.js"></script>
    3. Add the component to your HTML:

      <some-component></some-component>
    npm install some-package-name
  9. Use properties, loops, and conditionals in templates

    master

    LitElement templates (via lit-html) support dynamic content using JavaScript expressions:

    • Properties: Insert property values using ${this.propName}.
    • Loops: Iterate over arrays using .map(). For stateful or expensive repeated elements, consider the repeat directive from lit-html.
    • Conditionals: Use ternary operators for conditional rendering.
  10. Deliver different builds using differential serving

    master

    Differential serving (or browser sniffing) uses the User-Agent request header to determine which bundle to serve.

    Pros: High performance as browsers only receive the specific bundle they need. Cons: Relies on a static list of supported features per browser and can be inaccurate if User-Agent headers are incorrect. The prpl-server project is a Node.js web server that supports this technique.

  11. Use lit-html directives

    master

    Since LitElement uses lit-html, you can use its directives. To use them, add lit-html as a direct dependency in your project to ensure version compatibility.

    Example using the until directive to handle asynchronous content:

    import { LitElement, html } from 'lit-element';
    import { until } from 'lit-html/directives/until.js';
    
    const content = fetch('./content.txt').then(r => r.text());
    
    // In your render method:
    html`${until(content, html`<span>Loading...</span>`)}`