首页 > web前端 > js教程 > 正文

使用 SSR 构建响应式 Web 组件

WBOY
发布: 2024-08-24 11:22:06
原创
238 人浏览过

传统的 Web 组件编写方式对 SSR(服务器端渲染)不太友好。在这篇文章中,我将向您展示如何构建与 SSR 和任何 JavaScript 框架(Vue、React、Svelte、Solid、Brisa)或 Vanilla JS 配合使用的反应式 Web 组件。

  • 简介
  • 使用 Brisa 编写 Web 组件
  • 构建 Web 组件
  • 在 Vanilla JS 项目中加载 Web 组件
  • Web 组件的 SSR
  • 请告诉我更多关于 Brisa 的信息...
  • Web 组件库创建者注意事项
  • 示例
  • 结论

介绍

我们将使用 Brisa Web 组件编译器。 Brisa 是一个 Web 框架,除了与 Next.js 或 Nuxt.js 等其他框架类似之外,还允许您构建与反应性信号、JSX 和 SSR 一起使用的反应式 Web 组件。

Build Reactive Web Components with SSR


Brisa 徽标

为此,您只需要在编写 Web 组件时了解 Brisa 的语法即可。 Brisa 尚未公开,因为它目前占 v0.1 路线图的 95.48%,但我们估计 1 个月内它将准备好发布,每个人都可以访问它。但是,即使它根本不公开,您也可以使用它来创建您自己的 Web 组件库。

使用 Brisa 编写 Web 组件

作为示例,我们将一如既往地编写一个计数器的 Web 组件,这是经典示例。

counter-wc.tsx

import type { WebContext } from "brisa";

export default function CounterWC(
  { start = 0, color = "#2cebcf" }: { start?: number; color?: string },
  { state, css }: WebContext,
) {
  const count = state(start);

  css`
    button {
      background-color: ${color};
      color: white;
      border: none;
      border-radius: 5px;
      padding: 10px;
      margin: 5px;
      cursor: pointer;
    }
    div {
      display: flex;
      justify-content: center;
      align-items: center;
    }
  `;

  return (
    <div>
      <button onClick={() => count.value++}>+</button>
      {count.value}
      <button onClick={() => count.value--}>-</button>
    </div>
  );
}
登录后复制

Brisa 使用文件名来了解选择器,这里选择器将是 counter-wc。

提示:虽然 Brisa 尚未公开,但您可以使用 TypeScript 类型来指导您如何编写 Web 组件。

在上面的示例中,状态用于创建信号,然后使用 .value 使其在 JSX 内具有反应性。 props 也是特殊信号,因为它们是只读的,所以不使用 .value 来使其更易于使用并更轻松地定义默认值,这是通过构建时优化完成的,类似于 React如果他们使用信号但反过来。

CSS 模板文字允许它对颜色属性的反应性变化做出反应。此示例之外的 CSS 模板文字对于轻松制作反应式动画非常有用。重要的是要记住,Web 组件与 Shadow DOM 一起使用,因此 CSS 不会影响页面的其余部分。

构建 Web 组件

要构建 Web 组件,您需要运行以下命令:

brisa build -w counter-wc.tsx
登录后复制

此命令将生成 2 个文件:

[ wait ]  ? building your standalone components...
[ info ]
[ info ]   Standalone components:
[ info ]   - build/counter-wc.client.js (670.00 B)
[ info ]   - build/counter-wc.server.js (842.00 B)
[ info ]
[ info ]   ✨  Done in 42.20ms.
登录后复制

这些文件不是 Web Component,它只是 Web Component 的渲染功能,在构建时优化为尽可能轻(出来的字节没有 gzip).

那么,我们如何加载 Web 组件呢?

在 Vanilla JS 项目中加载 Web 组件

为此,您需要使用 brisa/client 在 HTML 中添加 importmap,然后导入 counter-wc.client.js 文件:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Brisa Web Component Example</title>
    <script type="importmap">
      {
        "imports": {
          "brisa/client": "https://unpkg.com/brisa@latest/client-simplified/index.js"
        }
      }
    </script>
    <script type="module" src="https://unpkg.com/counter-wc@latest"></script>
  </head>
  <body>
    <counter-wc start="15"></counter-wc>
  </body>
</html>
登录后复制

这里只有渲染部分会被移植到每个 Web 组件文件中,而它们都将使用导入映射中定义的相同 Brisa 包装器,该包装器负责使用信号和 Shadow DOM 创建 Web 组件。

Web组件的SSR

借助 Declarative Shadow DOM,现在可以完成 Web 组件的 SSR。 counter-wc.server.js 文件已经使用此行为进行了编译,因此您只需将其导入到您的服务器上并在 HTML 中呈现它并使其适应您的服务器框架。

这是一个使用 Bun.js 或 Node.js 而不使用 JSX 的示例:

ssr.js

import { renderToString } from "brisa/server";
import { jsx } from "brisa/jsx-runtime";
import CustomCounter from "counter-wc/server";

const html = `
<!DOCTYPE html>
<html lang="en">
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Brisa Web Component Example</title>
    <script type="importmap">
    {
        "imports": {
            "brisa/client": "https://unpkg.com/brisa@latest/client-simplified/index.js"
        }
    }
    </script>
    <script type="module" src="https://unpkg.com/counter-wc@latest"></script>
    </head>
    <body>
        ${await renderToString(jsx(CustomCounter, { start: 10 }))}
    </body>
</html>
`;

console.log(html);
登录后复制

然后运行bun run ssr.js,您将看到使用声明式 Shadow DOM 渲染的 Web 组件的 HTML。

告诉我更多关于布里萨的事……拜托……

这些 Web 组件库与 Brisa 的集成是通过配置文件完成的:

import type { WebComponentIntegrations } from "brisa";

export default {
  "custom-counter": {
    client: "./path/to/web-component.client.js",
    server: "./path/to/web-component.server.js",
    types: "./path/to/web-component.types.d.ts",
  },
} satisfies WebComponentIntegrations;
登录后复制

这样,SSR 和 TypeScript 类型就会自动集成到您的项目中。您可以在任何服务器组件或另一个 Web 组件中使用该 Web 组件。

Build Reactive Web Components with SSR

如果您有兴趣了解更多信息,我邀请您订阅 Brisa 时事通讯,以接收有关 Brisa 的最新消息和更新。我们预计九月底即可准备好上线。

Note for Web Component library creators

We encourage you to try Brisa to create your own Web Component libraries. If you put the "made with Brisa" badge, we will put a link to your library on the Brisa page.


Build Reactive Web Components with SSR

<a href="https://brisa.build" target="_blank" rel="noopener noreferrer">
  <img
    width="150"
    height="42"
    src="https://aralroca.com/images/blog-images/brisa_badge.svg"
    alt="Made with Brisa"
  />
</a>
登录后复制

Example

If you want to see the GitHub repository of the example of the counter that we have explained in this article, you can take a look and use it as a reference for your own creations:

  • https://github.com/aralroca/counter-wc

Conclusion

In this post, we have seen how to build reactive Web Components that work with SSR and with any JavaScript framework or Vanilla JS. We have used Brisa to build the Web Component and we have seen how to load it in a Vanilla JS project and how to do SSR with it.

I hope you have enjoyed this post and that you have learned something new. If you have any questions, do not hesitate to ask me in the comments below. I will be happy to help you.

Happy coding and enjoy the rest of the summer! ??


Build Reactive Web Components with SSR

Enjoy the rest of the summer!

以上是使用 SSR 构建响应式 Web 组件的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!