Every developer should pay attention to the reusability of the code and the business isolation of the code, which can separate the business logic from the application architecture and improve the scalability of the system. And Web Component is such a technology that allows us to create an independent reusable component.

This article will walk through the process of creating a generic Web Component using Svelte. “Universal” means that the component is not limited to Svelte applications, but can also be used in any JavaScript application (such as Vue, React, etc.), and will also introduce some limitations of using Svelte to create Web Components.

What are Web Components?

Web Components allow us to create reusable, custom HTML elements that encapsulate style and functionality.

For example, we use the following code to create a navigation bar:

<style>
/* CSS code for our navbar */
</style>
<navbar>
<!-- Some long code for our navbar -->
</navbar>

If we use Web Component technology, we can define a custom element (such as ), and then you can use this element to display the navigation bar anywhere on the web page, and the style of this navigation bar is the same as that of other elements on the page are completely isolated and do not affect each other. And this technology is called Shadow DOM (shadow DOM).

What is Shadow DOM?

The Shadow DOM is a smaller, self-contained DOM that is rendered separately from the main DOM, allowing us to isolate styling and markup behavior into a single component. Shadow DOM essentially allows us to encapsulate and isolate component functionality, which we can style and script functionality individually without interfering with the rest of the application’s elements.

You probably have a basic understanding of Web Component, let’s write a simple component using Svelte.

Build Web Components

Preparation

In order to complete the rest of this article, you need to master the following knowledge:

  • Basic knowledge of HTML, CSS and JavaScript
  • Familiar with the command line operating environment
  • need a text editor
  • It is best to have some basic understanding of Svelte (you can see my previously translated article https://my.oschina.net/javayou/blog/5309554 )

start

In this article we will develop two components:

  • The first component is a card component, which receives three attributes: card title, card description, and picture. The component is named <my-card />
  • The second component is a styled button that receives a type The attribute of the button is used to determine the display style of the button. The component name is <cool-button />

At the same time, we will use two ways to publish components, one is to package into a single file, and the other is to publish each component into a separate file.

The image below shows what the two components look like after running:

Final Preview Of Instantiated Components

We start by creating a Svelte application and installing the necessary packages:

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

After the above command is executed, you can use the following command to start a test environment:

npm run dev

Then we open the browser to visit http://localhost:8080 You can see what a basic Svelte application looks like after running:

The Welcome Page Of The New Svelte Application

develop a component

The process of generating a generic Web Component using Svelte is similar to the process of creating a regular Svelte component, with some modifications.

To create our first card component, we first create a file src/Card.svelte And define the properties, styles and HTML tags of the component, the code is as follows:

<script>
  // component props
  // Camel case not supported for props, see drawback section.
  export let card_title, card_desc, card_img;
</script>

<main>
  <div class="card-container">
    <div class="card">
      <img src={card_img} alt="My product" />
      <div class="card-body">
        <div class="row">
          <div class="card-title">
            <h2>{card_title}</h2>
          </div>
        </div>
        <p>
          {card_desc}
        </p>
        <button>Do Something</button>
      </div>
    </div>
  </div>
</main>

<style>
 .card {
    max-width: 350px;
    border-radius: 5px;
    box-shadow: 0 4px 6px 0 #00000033;
    padding: 0 0 10px 0;
  }

  .card img {
    width: 100%;
    height: auto;
  }

  .card-body {
    padding: 5px 10px;
  }

  .card-body p {
    color: #575757;
    margin-bottom: 20px;
    font-size: 14px;
  }
</style>

You can use this card component in other components as follows (this step can be ignored):

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

<main>
  <Card
    card_title="My Card Title"
    card_desc="Lorem ipsum dolor…"
    card_img="path/to/my-image.png"
  />

</main>

Next is the button component, the file name /src/Button.svelte code show as below:

<script>
  // Component props
  export let type = "solid";
</script>

<button class={type == "solid" ? "btn-solid" : "btn-outline"}>
  <slot />
</button>

<style>
  button {
    padding: 10px;
    color: #fff;
    font-size: 17px;
    border-radius: 5px;
    border: 1px solid #ccc;
    cursor: pointer;
  }
  .btn-solid {
    background: #20c997;
    border-color: #4cae4c;
  }
  .btn-outline {
    color: #20c997;
    background: transparent;
    border-color: #20c997;
  }
</style>

The usage of this component is as follows (can be ignored):

import Button from "./Button.svelte";

<Button type="outline">Click me</Button>

Convert custom components to generic components

We need to convert custom Svelte components into common Web Components so that they can be used directly in other frameworks.

To do this transformation, we need to set the compiler to generate custom elements in the Svelte configuration file.Open rollup.config.js Add one in plugins compilerOptionsConfiguration item, add under this configuration item customElement: true Configuration information, as follows:

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

然后我们需要给两个组件分别定义一个元素名称,打开 Card.svelte 文件,在文件开头第一行插入如下内容:

<svelte:options tag="my-card" />

上述 tag 属性值代表组件的标签名称。

同样的,打开 Button.svelte 给第二个组件指定一个标签名称:

<svelte:options tag="cool-button" />

最后一步是在 main.js 中引入这两个组件,打开 /src/main.js 将里面的内容替换成如下两行:

import Button from "./Button.svelte";
import Card from "./Card.svelte";

这里我们已经完成了两个组件的开发步骤,下一步就是打包组件以便其他的应用可以使用这两个组件,打开命令行窗口进入项目所在目录执行如下命令:

npm run build

该命令将生成两个文件,分别是 build.js 和 build.map.js, 文件位于项目下的 /build 目录。其中build.js 是打包的两个组件,而 build.map.js  build.js源代码映射文件。

如果上述步骤顺利完成,我们就可以将 bundle.js 拷贝到一个新目录,然后创建一个 index.html 文件,内容如下:

<!DOCTYPE html>
<html>
  <head>
    <title>My website</title>
    <script src="./build.js"></script>
  </head>

  <body>
    <div class="container">
      <div class="row">
        <div class="col">
          <my-card
            card_title="Red Person"
            card_desc=" Lorem ipsum dolor sit, amet consectetur.."
            card_img="https://bit.ly/34B3zHX"
          >
          </my-card>
          <!-- Image credit - Shubham Dhage on unsplash.com -->
        </div>
        <div class="col">
          <div class="border-bottom py-5">
            <cool-button> Solid Cool Button </cool-button>
            <cool-button type="outline"> Outlined Cool Button </cool-button>
          </div>
        </div>
      </div>
    </div>
  </body>
</html>

这是一个再简单不过的 HTML 页面了,该页面使用了上述两个组件,在浏览器中显示为如下效果:

Components Displayed On Webpage

组件分割

在某些情况下我们不需要将多个组件打包到同一个 js 文件中,我们希望每个组件有一个独立的 js 文件。要实现这个场景只需在 rollup.config.js 的 input 和 output 中进行配置即可。

在 input 的配置中我们可以指定一个数组,数组的元素就是每个组件的文件路径,而 output 指定为输出的目录即可:

export default {
  input: ["src/Card.svelte", "./src/Button.svelte"],
  output: {
    format: "iife",
    dir: "public/build/",
  },
...

Execute again after modification npm run build we can see two files in the build directory Button.js and Card.js .

The method of use is similar to:

<script src="Button.js" type="module"></script>
<cool-button type="outline">Click Me</cool-button>

<!-- another-page.html -->
<script src="Card.js" type="module"></script>
<my-card card_title="..."></my-card>

main disadvantage

So far we have mastered the method of using Svelte to develop Web Components. This process is very simple. However, using Svelte to develop Web Components has some disadvantages as follows:

  • Component property names are not allowed to use camel case. For example, you may find that using a property name like cardTitle does not work properly, and camel case is the recommended naming style in JavaScript.This is a bug, but if you are using Vite, there is a workaround plugin can solve this problem.
  • You can’t reuse web components in Svelte without marking them – unfortunately you also have to mark every Svelte component you want to use in your custom web components
    join you have a Header.svelte file needs to be <my-header /> Component output, but at the same time this component depends on another Nav.svelte file, and Nav.svelte we do not want to output as a Web component, this problem makes us have to output Nav.svelte as a component, otherwise the program will report an error.Fortunately, this problem is now solved (see the here)we can solve this problem through configuration, although it does not look so cool, so be it, it is not impossible to use.
  • Browser Support Questions — JavaScript customElement API is the underlying API used to create Web Components. This API is currently not supported by all browsers. We need to introduce Polyfill to solve this file. For details, see webcomponents official .

Summarize

In this article, we learned how to use Svelte to create generic card and button components, generate bundle files, split them, and even reuse this component in separate HTML pages.

Try it yourself?

This article is translated from: Build web components with Svelte – LogRocket Blog

#Svelte #build #Web #Components #super #simple #convenient #Java #Freelancer #News Fast Delivery

Leave a Comment

Your email address will not be published. Required fields are marked *