Create Web Components for your Symfony app with Webpack Encore and LitElement
Web Components can be a great lightweight way to add some interactivity to your web applications. You can include components anywhere you use standard HTML: Static HTML, output form a CMS or a DXP, or a JavaScript framework like React or Vue. Web Components have had a long and winding road to where we are today, but I still believe they're worth investing in as a long term technology and they're here to stay.
LitElement is a part of the Polymer Project from Google that aims to make developing Web Components easier. LitElement can be installed from the standard JavaScript NPM packet repository, and you can either create a new project from scratch or adjust your existing implementation to include LitElement.
Many Symfony developers use Webpack Encore for their front end asset management. Adding Web Components to your Symfony project with Webpack Encore is straightforward. First install Webpack Encore (you'll need Node.js, etc.) and then add lit-element from npm using NPM or Yarn (used in the example below):
yarn add lit-element
Now the package is in place in front end dependencies (in package.sjon) and installed node_modules folder. Next create a file for a new component (in our example in assets/js/components/hello-world.js) and add this sample code for a component:
import {LitElement, html} from 'lit-element'; class HelloWorld extends LitElement { static get properties() { return { name: {type: String}, }; } constructor() { super(); this.name = 'World'; } render() { return html` <div>Hello ${this.name}!</div> `; } } customElements.define('hello-world', HelloWorld);
Next add a new entry to your main Webpack configuration (webpack.config.js):
Encore.addEntry("public-site", [ .... path.resolve(__dirname, "./assets/js/components/hello-world.js") ]);
With this in place the next time you run the encore development process your JavaScript assets will include the compiled LitElement code. Remember that you'll need to have the entry link tags defined in your main template (e.g. base.html.twig).
With this in place you can start using the element in your markup, like any HTML tag:
<h1>Web components test</h1> <hello-world name="Symfony user">
That's it for this blog post. For more information read the LitElement documentation. Might also be worthwhile to check the tutorial Creating a LitElement project.
eZ Platform is now Ibexa DXP
Ibexa DXP was announced in October 2020. It replaces the eZ Platform brand name, but behind the scenes it is an evolution of the technology. Read the Ibexa DXP v3.2 announcement blog post to learn all about our new product family: Ibexa Content, Ibexa Experience and Ibexa Commerce