Build Universal Web Components with LitElement
In this tutorial, I’ll be showing you how to create your first LitElement component and render it in a vanilla HTML file.
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:
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.