Share:
Subscribe and receive the latest news directly in your email.

Software DevelopmentProgramming

Web components for dummies

Desde el inicio de la programación los programadores hemos intentado reutilizar la mayor cantidad de código posible, no por ser flojos, claro está, sino por eficiencia pura y dura. Ganar tiempo es ganar eficiencia y dinero y eso lo sabemos todos… pero, ¿qué tiene que ver todo esto con los webcomponents?

Pues muy fácil, te lo resumo con un claro ejemplo. Si eres programador de front o estás un poco enterado de las nuevas tecnologías que se usan para desarrollar la parte visual de la aplicación, sabrás que existen varias formas de realizar tal desempeño. Desde usar simplemente HTML + CSS + JS para  crear por ejemplo un menú a usar algún framework como puede ser Angular, React o VueJs. Como ves existen diferentes maneras de solucionar el problema, aunque claro, si tienes una aplicación en VueJs y otra en Angular, aunque el menú sea igual visual y funcionalmente tendrías que programar dos veces, ¿cierto? Pues con nuestros queridos Webcomponents, ¡solo tendrás que hacerlo una vez! Sí, parece increíble pero es así, como hemos mencionado anteriormente, desde siempre hemos querido reutilizar el mismo código lo máximo posible, por lo tanto ahora estamos evolucionando a una tendencia en la que si un programador desarrolla el componente menú en Angular con unas ciertas peculiaridades que veremos más adelante, puede importar ese menú tanto a VueJS, React o incluso un HTML en limpio.

Si no me creeis acompañadme en esta pequeña introducción en la que os mostraré cómo un menú programado en angular, podemos usarlo luego en un HTML “limpio”.

Para empezar vamos a crear un proyecto Angular que se componga de un componente menú.

Primero creamos el proyecto:

ng new post-menu –prefix ng-post-menu

Ahora con el proyecto creado agregamos la dependencia de Angular de elements la cual nos facilita la creación de este webcomponent agregando el polyfill document-register-element.js

ng add @angular/elements

 

And we're going to create our menu component with some instructions:

ng generate component post-menu

We have added encapsulation to our component and we will tell it to be Emulated. Angular by default does not use Shadow DOM to encapsulate its components, in order to facilitate compatibility between multiple browsers that do not yet support this feature natively, but we can specify it.

 

We're going to create a simple menu in this component using Bootstrap. Since the purpose of this post isn't to teach you how to create the menu or use Bootstrap, we'll skip some steps.

Now that our menu component is working, we need to tweak our app module so that Angular compiles our application as a web component.

Adding the following code:

 constructor(

    private injector: Injector

  ) {

    const imagenEspacio = createCustomElement(PostMenuComponent, { injector });

    customElements.define(‘ng-post-menu-post-menu’, imagenEspacio);

  }

  ngDoBootstrap() {}

 

All that remains is to compile the project:

ng build –prod

This creates the dist/post-menu folder. The following .js files will appear inside it.

  • main

  • polyfills

  • runtime

  • scripts

Our goal is firstly to put all these js files together into one that we will call, for example, post-menu.js.

With this, we have almost everything we need. The project may also require styles and images that will exist in the dis/post-menu folder; these would also need to be imported into the new project where we want to insert our web component.

Finally, we'll create an empty HTML file and import our menu, resulting in the following:

 

Finally displaying our menu on a "blank" HTML page

This concludes our brief introduction to web components. Will they be the future? Will this type of technology become the norm, allowing us to abstract away from frameworks? That remains to be seen. While it may seem simple and appealing, it's still in its early stages and will need to evolve. However, it's already being used, and it's up to you to learn and continue progressing.

 

At SOLTEL, we have an innovative approach to technology because we are passionate about it. Our extensive experience working with diverse technologies over many years helps us approach projects with a broad perspective and become true technology partners for our clients.

References:

Other news