Why lit is 🔥
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.
- Authors
- Name
- Lucien Immink
- linkedinLucien Immink
- twitter@lucienimmink
- Github
- githublucienimmink
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.
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).
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
The Test Automation Meetup
PLEASE RSVP SO THAT WE KNOW HOW MUCH FOOD WE WILL NEED Test automation is a cornerstone of effective software development. It's about creating robust, predictable test suites that enhance quality and reliability. By diving into automation, you're architecting systems that ensure consistency and catch issues early. This expertise not only improves the development process but also broadens your skillset, making you a more versatile team member. Whether you're a developer looking to enhance your testing skills or a QA professional aiming to dive deeper into automation, RSVP for an evening of learning, delicious food, and the fusion of coding and quality assurance! 🚀🚀 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: The Power of Cross-browser Component Testing - Clarke Verdel, SR. Front-end Developer at iO How can you use Component Testing to ensure consistency cross-browser? Second Round of Talks: Omg who wrote this **** code!? - Erwin Heitzman, SR. Test Automation Engineer at Rabobank How can tests help you and your team? Beyond the Unit Test - Christian Würthner, SR. Android Developer at iO How can you do advanced automated testing for, for instance, biometrics? RSVP now to secure your spot, and let's explore the fascinating world of test automation together!
| Coven of Wisdom - Amsterdam
Go to page for The Test Automation MeetupCoven of Wisdom - Herentals - Winter `24 edition
Worstelen jij en je team met automated testing en performance? Kom naar onze meetup waar ervaren sprekers hun inzichten en ervaringen delen over het bouwen van robuuste en efficiënte applicaties. Schrijf je in voor een avond vol kennis, heerlijk eten en een mix van creativiteit en technologie! 🚀 18:00 – 🚪 Deuren open 18:15 – 🍕 Food & drinks 19:00 – 📢 Talk 1 20:00 – 🍹 Kleine pauze 20:15 – 📢 Talk 2 21:00 – 🙋♀️ Drinks 22:00 – 🍻 Tot de volgende keer? Tijdens deze meetup gaan we dieper in op automated testing en performance. Onze sprekers delen heel wat praktische inzichten en ervaringen. Ze vertellen je hoe je effectieve geautomatiseerde tests kunt schrijven en onderhouden, en hoe je de prestaties van je applicatie kunt optimaliseren. Houd onze updates in de gaten voor meer informatie over de sprekers en hun specifieke onderwerpen. Over iO Wij zijn iO: een groeiend team van experts die end-to-end-diensten aanbieden voor communicatie en digitale transformatie. We denken groot en werken lokaal. Aan strategie, creatie, content, marketing en technologie. In nauwe samenwerking met onze klanten om hun merken te versterken, hun digitale systemen te verbeteren en hun toekomstbestendige groei veilig te stellen. We helpen klanten niet alleen hun zakelijke doelen te bereiken. Samen verkennen en benutten we de eindeloze mogelijkheden die markten in constante verandering bieden. De springplank voor die visie is talent. Onze campus is onze broedplaats voor innovatie, die een omgeving creëert die talent de ruimte en stimulans geeft die het nodig heeft om te ontkiemen, te ontwikkelen en te floreren. Want werken aan de infinite opportunities van morgen, dat doen we vandaag.
| Coven of Wisdom Herentals
Go to page for Coven of Wisdom - Herentals - Winter `24 editionMastering 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