Why lit is 🔥

By Lucien Immink

7 min read

Every day a new JavaScript library is born, every week a new framework arrives and every month a front-end developer needs to rewrite a date picker 😢 LIT is a modern library for creating component libraries, design systems but also sites and apps. LIT components are web components and as such work anywhere you use HTML.

Why lit is 🔥
Authors

In the fast-changing world of front-end development it's hard to keep up with all the new libraries and frameworks out there that promise to be the next big thing. Frameworks tend to do a lot of heavy lifting but also tend to not agree with each other. As a developer this means that you might have to rewrite code to swap out the old framework for the new. It becomes more of an issue if you must rewrite nearly all of your code if the frameworks can't live together.

Schema of the elements of a URL

Luckily things are changing (again). With architectural choices like micro frontends it is possible to break up a complex and large code base in logical smaller parts. What if those parts share a few components? Which framework should you use? It should be interoperable and future ready. This is one example where web components shine as you can use those anywhere you use HTML.

What is LIT?

LIT is a small library on top of web components and literals. Created to skip some of the boilerplate that native DOM manipulation, shadow DOM, custom elements and templates bring to the table. Next to skipping the boilerplate LIT adds a few utilities for reactivity and productivity. Every feature is designed with the web platform in mind. Not fighting but embracing the platform.

At just 6KB (minified and compressed) LIT doesn't add much overhead to a bundle while it gives all the tools and features to create components for component libraries but also web sites and apps.

Rendering is handled by using a web platform standard called literals which makes LIT only touch the dynamic parts of the DOM when it updates, there is no need to rebuild a (virtual) tree and diff with the DOM.

Literals

Literals represent a value in JavaScript. fixed (no variable) value that you literally provide in JavaScript. Literals include:

  • Array literals (e.g.: let list = ['cat', 'dog', 'catdog'])
  • Boolean literals (e.g.: true)
  • Numeric literals (e.g.: 1337)
  • Object literals (e.g.: let person = { name: 'Lucien', surname: 'Immink', gender: 'male'})
  • RegExp literals and (e.g.: let re = /ab+c/)
  • String literals (e.g.: let str = 'Hello')

A string literal is everything between a single (') or double (") quotation mark. With the introduction of ECMAScript 2015 (ES6) another literal was added: the template literal which provide an easy way to create multiline strings and perform string interpolation. Template literals are string literals and allow embedded expressions. Template literals use the backtick (`) as delimiter. Some examples of the template literal:

const str = `Hello`
const multi = `Hello
wonderful
world`
const expression = `Hello ${type} world`
taggedFunction`Hello ${type} world`

The tagged template literal calls the function with that name (in this case taggedFunction()) with the template as the first argument and the substitution values as the subsequent arguments.

The browser has support for template literals built in. This includes optimizations such as only updating the dynamic part of a template literal instead of the whole literal. What if literals are used for creating UIs?

Web Components

Since LIT extends web components it inherits all the positive effects web components have: LIT works everywhere you use HTML, with any framework or none at all. This also means that migrating from a specific framework to LIT can be done one component at a time, no need to rewrite everything from the start. What if web components are used for creating components?

What is interesting about LIT?

Take template literals for rendering templates and combine them with web components for lifecycle management, event handling and encapsulation of style and function you get LIT.

⚠️ Note that all examples in this article will use TypeScript but LIT can also be written using pure JavaScript. ⚠️
import { html, css, LitElement } from 'lit'
import { customElement, property } from 'lit/decorators.js'

@customElement('hello-world')
export class HelloWorld extends LitElement {
  static styles = css`
    p {
      color: green;
    }
  `

  @property()
  type = 'wonderful'

  render() {
    return html`<p>Hello ${this.type} world</p>`
  }
}
<!DOCTYPE html>
<html lang="en">
  <body>
    <hello-world type="amazing">Light DOM fallback</hello-world>
  </body>
</html>

This <hello-world> example comes in at 235 bytes with 6KB for LIT (minified and compressed).

Schema of the elements of a URL

Start saying hello to the world by cloning the source code.

Decorators

If you are unfamiliar with @customElement(...) and @property; they are called decorators and a decorator wraps a piece of code with another. A concept also known as functional composition or higher-order functions. Classes and their properties are not the same as functions and cannot simply be wrapped using functional composition. The decorator adds support for wrapping classes and properties. The example wraps HelloWorld with the functionality from LitElement, transforming the HelloWorld class to a LIT element. By applying the @property decorator to the type property it's functionality is extended so it can be used as a reactive custom element property.

Should you want a reactive property that is purely internal (so not available as property or attribute on the custom element) but still reactive to change you can decorate the property with the @state decorator.

Decorators are (for now) only available in TypeScript.

Advanced templating

All is fine and well if only Hello wonderful world needs to be printed; but most of the time more complex templating is needed. Template literals can be nested and contain logic. Combined with the tagged template literal more complex templates can be achieved

renderHeader() {
    return html`<div>Some fancy header</div>`
}
renderFooter() {
    return html`<div>Some fancy footer</div>`
}

render() {
    return html`
        ${this.renderHeader()}
        <p>What a nice ${new Date().getHours() < 12 ? html`morning` : html`day`} </p>
        ${this.renderFooter()}
    `
}

But why stop there? Well one reason is readability of course! And reusability could be another reason. Split this template up in 3 separate components will improve both the readability and reusability. Let's take a look at the my-header first.

import { html, LitElement } from 'lit'
import { customElement } from 'lit/decorators.js'

@customElement('my-header')
export class MyHeader extends LitElement {
  render() {
    return html`<div>Some fancy header</div>`
  }
}

The same applies for my-footer. Both are now a web component, usable in other LIT elements or directly on a HTML page or imported into a React, angular, vue... HTML based web application.

import { LitElement, html } from 'lit'
import { customElement } from 'lit/decorators.js'

import './my-header.js'
import './my-footer.js'

@customElement('my-page')
class MyPage extends LitElement {
  render() {
    return html`
      <my-header></my-header>
      <p>What a nice ${new Date().getHours() < 12 ? html`morning` : html`day`}</p>
      <my-footer></my-footer>
    `
  }
}

Event handling

Handling events with LIT is quite straightforward. The following example adds a click handler to a button and the result is automatically updated in the counter:

import { html, LitElement } from 'lit'
import { customElement, property } from 'lit/decorators.js'

@customElement('my-counter')
export class HelloWorld extends LitElement {
  @property()
  counter: number = 0

  addCount() {
    this.counter += 1
  }

  render() {
    return html`
      <button @click=${this.addCount}>Add more</button>
      <p>counter is now at: ${this.counter}</p>
    `
  }
}

Add the @eventOptions decorator on the addCount() function to add any of the options passable by addEventListener. LIT uses and embraces the web platform. No need to learn a new API here.

@eventOptions({ passive: true })
addCount()

Styling

Styling in LIT uses template literals as well. Lit components use a shadow DOM making styling straightforward.

import { LitElement, html, css } from 'lit'
import { customElement } from 'lit/decorators.js'

@customElement('my-element')
export class MyElement extends LitElement {
  static styles = css`
    :host {
      font-size: 2em;
      padding: 1em;
      border: 0.25em solid var(--blue, blue);
    }
    p {
      color: var(--blue, blue);
    }
  `
  render() {
    return html`<p>I am blue da ba dee! ®eiffel 65</p>`
  }
}

:host is the selector for the shadow-DOM root, CSS variables are part of the web platform and can be used in LIT as well. CSS variables make it easy to create themes but also to better adept to the styling of the page that includes the LIT component.

Sharing styles between components can easily be achieved by creating a separate file that exports the shareable style

// file: button-styles.ts
import { css } from 'lit'

export const buttonStyles = css`
  .primary-button {
    color: var(--text-colour);
    color: var(--primary-colour);
  }
  .primary-button:disabled {
    opacity: 0.6;
    pointer-events: none;
  }
`
import { css, LitElement } from 'lit'
import { customElement } from 'lit/decorators.js'
import { buttonStyles } from './button-styles.ts'

@customElement('my-element')
export class MyElement extends LitElement {
  static styles = [
    buttonStyles,
    css`
      :host {
        display: block;
        border: 1px solid black;
      }
    `,
  ]
}

That sounds too good to be true

...and perhaps it is. LIT is relatively new, as are web components. A certain widely used framework that uses a virtual DOM implementation has had a bumpy ride when it comes to web component interoperability.

The eco system for LIT dwarfs compared to today's big three. Having the ability to export both Vue and Angular components as web components and having both playing nice with web components might just change things in the future. LIT can use any web component and can provide web components for any other framework as long as it uses HTML and the web platform.

LIT is working on making server side renderable components part of the new major version release but they have released a package with LIT components can already be tested server-side.

LIT is not a replacement for everything web related, but what has ever been? Since it sticks close to the platform it evolves with the platform and new features, APIs and functionalities work the day they become available in the browser.

Closing thought

LIT is a small library on top of web components and literals. Created to skip some of the boilerplate that native DOM manipulation, shadow DOM, custom elements and templates bring to the table. Next to skipping the boilerplate LIT adds a few utilities for reactivity and productivity. Every feature is designed with the web platform in mind. Not fighting but embracing the platform.

At just 6KB (minified and compressed) LIT doesn't add much overhead to a bundle while it gives all the tools and features to create components for component libraries but also web sites and apps.


Upcoming events

  • Mastering Event-Driven Design

    PLEASE RSVP SO THAT WE KNOW HOW MUCH FOOD WE WILL NEED Are you and your team struggling with event-driven microservices? Join us for a meetup with Mehmet Akif Tütüncü, a senior software engineer, who has given multiple great talks so far and Allard Buijze founder of CTO and founder of AxonIQ, who built the fundaments of the Axon Framework. RSVP for an evening of learning, delicious food, and the fusion of creativity and tech! 🚀 18:00 – 🚪 Doors open to the public 18:15 – 🍕 Let’s eat 19:00 – 📢 Getting Your Axe On Event Sourcing with Axon Framework 20:00 – 🍹 Small break 20:15 – 📢 Event-Driven Microservices - Beyond the Fairy Tale 21:00 – 🙋‍♀️ drinks 22:00 – 🍻 See you next time? Details: Getting Your Axe On - Event Sourcing with Axon Framework In this presentation, we will explore the basics of event-driven architecture using Axon Framework. We'll start by explaining key concepts such as Event Sourcing and Command Query Responsibility Segregation (CQRS), and how they can improve the scalability and maintainability of modern applications. You will learn what Axon Framework is, how it simplifies implementing these patterns, and see hands-on examples of setting up a project with Axon Framework and Spring Boot. Whether you are new to these concepts or looking to understand them more, this session will provide practical insights and tools to help you build resilient and efficient applications. Event-Driven Microservices - Beyond the Fairy Tale Our applications need to be faster, better, bigger, smarter, and more enjoyable to meet our demanding end-users needs. In recent years, the way we build, run, and operate our software has changed significantly. We use scalable platforms to deploy and manage our applications. Instead of big monolithic deployment applications, we now deploy small, functionally consistent components as microservices. Problem. Solved. Right? Unfortunately, for most of us, microservices, and especially their event-driven variants, do not deliver on the beautiful, fairy-tale-like promises that surround them.In this session, Allard will share a different take on microservices. We will see that not much has changed in how we build software, which is why so many “microservices projects” fail nowadays. What lessons can we learn from concepts like DDD, CQRS, and Event Sourcing to help manage the complexity of our systems? He will also show how message-driven communication allows us to focus on finding the boundaries of functionally cohesive components, which we can evolve into microservices should the need arise.

    | Coven of Wisdom - Utrecht

    Go to page for Mastering Event-Driven Design
  • The Leadership Meetup

    PLEASE RSVP SO THAT WE KNOW HOW MUCH FOOD WE WILL NEED What distinguishes a software developer from a software team lead? As a team leader, you are responsible for people, their performance, and motivation. Your output is the output of your team. Whether you are a front-end or back-end developer, or any other discipline that wants to grow into the role of a tech lead, RSVP for an evening of learning, delicious food, and the fusion of leadership and tech! 🚀 18:00 – 🚪 Doors open to the public 18:15 – 🍕 Let’s eat 19:00 – 📢 First round of Talks 19:45 – 🍹 Small break 20:00 – 📢 Second round of Talks 20:45 – 🙋‍♀️ drinks 21:00 – 🍻 See you next time? First Round of Talks: Pixel Perfect and Perfectly Insane: About That Time My Brain Just Switched Off Remy Parzinski, Design System Lead at Logius Learn from Remy how you can care for yourself because we all need to. Second Round of Talks: Becoming a LeadDev at your client; How to Fail at Large (or How to Do Slightly Better) Arno Koehler Engineering Manager @ iO What are the things that will help you become a lead engineer? Building Team Culture (Tales of trust and positivity) Michel Blankenstein Engineering Manager @ iO & Head of Technology @ Zorggenoot How do you create a culture at your company or team? RSVP now to secure your spot, and let's explore the fascinating world of design systems together!

    | Coven of Wisdom - Amsterdam

    Go to page for The Leadership Meetup
  • Coven of Wisdom - Herentals - Spring `24 edition

    Join us for an exciting web technology meetup where you’ll get a chance to gain valuable insights and knowledge about the latest trends in the field. Don’t miss out on this opportunity to expand your knowledge, network with fellow developers, and discover new and exciting possibilities. And the best part? Food and drinks are on us! Johan Vervloet - Event sourced wiezen; an introduction to Event Sourcing and CQRS Join me on a journey into the world of CQRS and Event Sourcing! Together we will unravel the misteries behind these powerful concepts, by exploring a real-life application: a score app for the 'Wiezen' card game.Using examples straight from the card table, we will delve into the depths of event sourcing and CQRS, comparing them to more traditional approaches that rely on an ORM.We will uncover the signs in your own database that indicate where event sourcing can bring added value. I will also provide you with some tips and pointers, should you decide to embark on your own event sourcing adventure. Filip Van Reeth - WordPress API; "Are you talking to me?" What if the WordPress API could be one of your best friends? What kind of light-hearted or profound requests would it share with you? In this talk, I would like to introduce you to it and ensure that you become best friends so that together you can have many more pleasant conversations (calls). Wanna be friends? Please note that the event or talks will be conducted in Dutch. Want to give a talk? Send us your proposal at meetup.herentals@iodigital.com 18:00 - 19:00: Food/Drinks/Networking 19:00 - 21:00: Talks 21:00 - 22:00: Networking Thursday 30th of May, 18h00 - 22h00 CET iO Campus Herentals, Zavelheide 15, Herentals

    | Coven of Wisdom Herentals

    Go to page for Coven of Wisdom - Herentals - Spring `24 edition

Share