DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 967,611 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Cover image for Build Universal Web Components with LitElement
Saji Wang for Codesphere Inc.

Posted on • Updated on

Build Universal Web Components with LitElement

Written by Lior Ben David.


It feels like every day a new web framework appears fighting for your attention. With all these different frameworks, however, you might find yourself rewriting code to get your components working right on a new framework.

If you're looking to create a universal component library, look no further than LitElement, a simple base class for creating cross-library components with their own embedded styling and javascript.

In this tutorial, I'll be showing you how to create your first LitElement component and render it in a vanilla HTML file.


Setup

To get started, we're going to create a new npm project with

npm init

We are then going to install lit-element and Polymer with:

npm i lit-element polymer

Polymer isn't 100% necessary, but will just allow us to test this component easily.

Finally, let's create an index.html and a card.js

touch index.html card.js

Code

Our index.html can be as simple as:

Note that all we need is the inclusion of the script tags to our custom component, as well as the component itself of course.

Our Card.js can then look as follows:

And that's all it takes! We can then serve this page live with:

polymer server

And lo and behold:

Image description


Using Lit ElementΒ Anywhere

We can then use this exact same LitElement class in React, Vue, Angular, or whatever web framework you or your fellow developers prefer. All that needs to be done is to install Litelement and then access the custom tag you created.

So what do you think? Do you see a benefit of using LitElement, or is this just an extraneous layer? Let us know down below.

As always, happy coding from your friends at Codesphere, the most intuitive cloud provider on the market.

Top comments (1)

Collapse
 
justinfagnani profile image
Justin Fagnani

I'd recommend Web Dev Server over the Polymer server, which is very unmaintained at this point.

Web Dev Server: modern-web.dev/docs/dev-server/ove...

Classic DEV Post from 2020:

js visualized

πŸš€βš™οΈ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! πŸ₯³

Happy coding!