首頁 > 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學習者快速成長!