What is a Web Component?

Web Components are a set of several Web technologies that allow you to create personalized, reusable and unitary elements. This means that their code and styles are isolated for each component, so they can be used within any web page or application.

Let’s take a look at how a Web Component is composed:

An example of a Web Component as represented in the sources of a web page
  1.  Web Components use the Custom Element API to create tags with a custom name.
  2. They use the Shadow DOM to isolate functionality and styles in a DOM tree hidden from the rest of the page.
  3. They can consist of HTML Templates such as <slot> and <template> not displayed on the page…
  4. … but which allow, among other things, to add content to your component when it is used.

These functionalities are available on almost all browsers, and you could even use them natively to create your Web Components.

This can be difficult, however, because you will also have to take into account and manage the different stages of the life cycle of the component thus created.

Fortunately, there are a large number of solutions allowing the creation of these Web Components, dedicated to their development or not, as presented in this comparison of the different tools .

In this article, we’ll explore how to develop Web Components using Svelte, a minimalistic, powerful, and increasingly popular framework.

What is Svelte?

Svelte is a framework launched in 2016, used to create component-based web applications.

This framework has the particularity of not using the Virtual DOM, thus directly modifying the DOM , as well as going through a compilation to pure JavaScript , allowing to have a lighter and faster application since the page is no longer obliged to embed the code of the framework.

See also  My TOP image compression tools

Svelte also offers elements that allow to use much less code than other frameworks like React or Vue, which also benefits the lightness of the deliverables.

Develop a Slim component

As we told you earlier, the objective of this tutorial is to create a component listing the latest Korben.info articles . To do this, we will use the RSS feed provided free of charge: https://korben.info/feed .

We’ll start by creating a standard Svelte component, and then we’ll see how to make this component work as a Web Component.

There are several methods to create a Svelte project using different build tools. Today, we’ll use the default template recommended by Svelte sveltejs/template , which will initialize our project with a rollup.js configuration and an example component.

So let’s start by getting and installing this template, using the degit utility :

npx degit sveltejs/template web-component-korben
cd web-component-korben
npm install

This generates a project with the following structure:

You can then run the npm run dev command to launch and expose your application:

Our first Hello World in Svelte!

Let’s now create a new Korben.svelte file next to the main.js file , composed of a <script> tag containing the logic of the component used to retrieve the articles, a <style> tag in which we define the style sheet specific to this component and finally the HTML structure of the component.

<script>
const CORS_PROXY_URL = '<https://corsanywhere.herokuapp.com/>';
const KORBEN_FEED_URL= '<https://korben.info/feed>';
const RSS_URL = CORS_PROXY_URL + KORBEN_FEED_URL;

/**
* Fonction de récupération des articles
*/
async function fetchKorbenArticles(){
	...
}
</script>

<div>
  ...
	{#await getKorbenArticlesFromFeed()}
    <div class="spin" />
  {:then items}
    {#if items && items.length > 0}
      {#each items as item}
        <div class="article">
          <img
            class="image"
            src={articleImageUrl(item)}
            height={articleImageHeight(item)}
            width={articleImageWidth(item)}
            alt={articleTitle(item)}
          />
          <div class="details">
            <div class="title">
              {articleTitle(item)}
            </div>
            <div class="description">
              {@html articleDescription(item)}
            </div>
          </div>
        </div>
      {/each}
    {/if}
  {:catch error}
    <p style="color: red">{error.message}</p>
  {/await}
	...
</div>

<style>
	/* Styles du composant */
</style>

In the HTML section of our component, you can see some of Svelte’s many directives:

  • {#await} to process promises and observables, here the asynchronous return from fetchKorbenArticles(). You can also observe the use of {:catch} , which allows us to handle errors raised by our article fetching method.
  • {#if} to handle conditions.
  • {#each} to iterate over arrays.
  • {@html } to insert HTML content.
See also  How to Find Your Dream Discord Server

Our component ready, now it’s time to import it and display it in our root component: App.svelte

<script>
import Korben from "./Korben.svelte";
</script>

<Korben />

Once done, you should be able to see the list of the latest articles from Korben.info in your browser.

Our widget in action

Transform our component into a Web Component

To be able to be used as a Web Component , we will have to configure our component to be used as a Custom Element , and not as a Slim element.

Let’s start by defining the name of our HTML tag, by defining the tag at the beginning of our Korben.svelte file :

<svelte:options tag="korben-rss-feed" />

<script>
...

We also need to tell our compiler that we need to compile elements that are part of the Custom Element API, by modifying the rollup.config.js configuration file and adding the customElement property to it in the compilation options:

plugins: [
    svelte({
      compilerOptions: {
        dev: !production,
        customElement: true,
...

By executing the npm run build command , we can now build a bundle of our application in vanilla JavaScript, i.e. without additional libraries. This will produce a public/build/bundle.js file which we can then insert into any HTML page.

<html>
	<head>
	    <title>Test Korben korben-rss-feed</title>
	    <script src="../public/build/bundle.js"></script>
	</head>
	
	<body>
	    <div class="container">
	        <div class="row">
	            <div class="col">
	                <korben-rss-feed></korben-rss-feed>
	            </div>
	        </div>
	    </div>
	</body>
</html>

That said, our component here has been compiled with all the other components of our project, and we would rather our deliverable not contain any code not used by our Web Component, so that it is as light as possible.

To do this, we just need to modify our rollup.config.js file , to pass our component file as input and not the application entry point:

export default {
	/* input: 'src/main.js', */
	input: 'src/Korben.svelte',
...

During construction, a new public/build/bundle.js file is then created, which this time contains only the code strictly necessary for our Web Component, which can then be integrated into any site.

See also  Subloader - Retrieve the subtitles of a movie or a series with a simple right click

It’s good, you now know how to create a Web Component with Svelte!

Integrate the Web Component into an existing site

Your compiled component, it is now easy to integrate it into any website

<section class="news-last_header">
  <h3>Les derniers articles Korben</h3>
  <a href="https://korben.info" target="_blank">VOIR TOUS SES ARTICLES <i class="icon-right"></i></a>
</section>

<section class="news-last_list" style="height: 170px;">
	<script src="./scripts/bundle.js"></script>
	<korben-rss-feed direction="row" style="position:absolute; left:0"></korben-rss-feed>
</section>

With for rendering:

Here, as you can see, it is very simple to create our own Web Components using Svelte, and it is up to you to create and share your component ideas

You can find the code of our component on Github.

Source korben.info

If you liked this article, please subscribe to our reddit community to discuss it. You can also find us on Twitter and Facebook.

5/5 - (1 vote)