Marcus Hellberg

Creating a LitElement project

In this series of tutorials, you learn how to build an application using Web Components and LitElement. The topics we cover are:

  1. Starting a LitElement project

  2. lit-html templating and events

  3. State management with Redux

  4. Navigation and code splitting

  5. PWA and offline

Todo tutorial app using LitElement, lit-html, and redux.
Figure 1. The app we are building

Video tutorial for this part

Download the LitElement starter

We are using Webpack to serve the application during development and for building the application for production. This tutorial does not cover Webpack configuration. Instead, we start with a pre-configured project skeleton.

Once you have downloaded the starter, unzip it and run:

$ npm install
$ npm run dev

Then start the development server and navigate to http://localhost:8080.

If everything went well, you should see the empty application. You are now ready to get started!

Empty starter app running on localhost

Creating the first component

Start by installing LitElement.

$ npm install --save lit-element

Create a new folder views in the src folder, and create a file todo-view.js in it. We always name our files the same as their HTML tag names to make it easier to navigate the source.

views/todo-view.js
import { LitElement, html } from 'lit-element'; (1)

class TodoView extends LitElement { (2)
  render() {
    return html` (3)
      <p>todo-view</p>
    `;
  }
}

customElements.define('todo-view', TodoView); //(4)
  1. Import the LitElement base class and html template function

  2. Create a class for the component, extending LitElement

  3. Define a template in the render() function using the html template function.

  4. Associate the component implementation with a HTML tag using the CustomElements registry.

Note
Tag names need to have a dash (-) to avoid naming collisions with native HTML elements.

Once we have a component definition, we need to import it to the browser is aware of it. The Webpack configuration takes care of including the JavaScript in our app.

index.js
import './styles.css';
import './views/todo-view.js';

Now we can use the component like any other HTML tag. Let’s add it to the <main> section of the index file.

index.html
...
  <main>
    <todo-view></todo-view>
  </main>
...
Note
Custom elements need to have a closing tag.

If you still have the development server (npm run dev) running, you should see the new component running:

LitElement running in the application

Next

In the next tutorial, we will implement the todo view.

Vaadin is an open-source framework offering the fastest way to build web apps on Java backends
GET STARTED

Comments (6)

Marcus Hellberg
2 years ago May 10, 2019 12:49pm
Tomasz Jagusz
1 year ago Aug 17, 2020 1:32pm