SSR을 사용하여 반응형 웹 구성 요소 구축

WBOY
풀어 주다: 2024-08-24 11:22:06
원래의
238명이 탐색했습니다.

웹 구성 요소를 작성하는 전통적인 방식은 SSR(Server Side Rendering)에 그다지 친숙하지 않습니다. 이 게시물에서는 SSR 및 모든 JavaScript 프레임워크(Vue, React, Svelte, Solid, Brisa) 또는 Vanilla JS와 작동하는 반응형 웹 구성 요소를 구축하는 방법을 보여줍니다.

  • 소개
  • Brisa로 웹 컴포넌트 작성
  • 웹 구성요소 구축
  • 바닐라 JS 프로젝트에서 웹 구성 요소 로드
  • 웹 컴포넌트의 SSR
  • 브리사에 대해 더 알려주세요... 부탁드립니다...
  • 웹 구성 요소 라이브러리 작성자를 위한 참고 사항
  • 결론

소개

브리사 웹 컴포넌트 컴파일러(Brisa Web Component Compiler)를 사용할 예정입니다. Brisa는 Next.js 또는 Nuxt.js와 같은 다른 프레임워크와 유사할 뿐만 아니라 JSX 및 SSR을 사용하여 반응성을 위한 신호로 작동하는 반응형 웹 구성 요소를 구축할 수 있는 웹 프레임워크입니다.

Build Reactive Web Components with SSR


브리사 로고

이를 위해서는 웹 컴포넌트 작성 시 Brisa의 구문만 알면 됩니다. Brisa는 현재 v0.1 경로 맵의 95.48%이므로 아직 공개되지 않았지만, 1개월 안에 출시 준비가 완료되어 누구나 액세스할 수 있을 것으로 예상됩니다. 그러나 전혀 공개되지 않더라도 이미 이를 사용하여 자신만의 웹 구성 요소 라이브러리를 만들 수 있습니다.

Brisa를 사용하여 웹 구성 요소 작성

예를 들어, 항상 그렇듯이 전형적인 예인 카운터의 웹 구성 요소를 작성해 보겠습니다.

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 유형을 사용하여 웹 구성 요소 작성 방법을 안내할 수 있습니다.

위 예에서 상태는 신호를 생성하는 데 사용되며 .value를 사용하여 JSX 내에서 반응하도록 만듭니다. props는 읽기 전용이기 때문에 특수 신호이기도 합니다. .value는 더 쉽게 사용하고 기본값을 더 쉽게 정의하는 데 사용되지 않습니다. 이는 React와 유사하게 빌드 시간 최적화를 통해 수행됩니다. 신호를 사용하고 있다면 그 반대입니다.

CSS 템플릿 리터럴을 사용하면 색상 속성의 경우 반응형 변경 사항에 반응할 수 있습니다. 이 예제 이외의 CSS 템플릿 리터럴은 반응형 애니메이션을 쉽게 만드는 데 매우 유용합니다. 웹 구성 요소가 Shadow DOM과 함께 작동하므로 CSS가 페이지의 나머지 부분에 영향을 미치지 않는다는 점을 기억하는 것이 중요합니다.

웹 구성 요소 구축

웹 구성 요소를 빌드하려면 다음 명령을 실행해야 합니다.

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.
로그인 후 복사

이러한 파일은 웹 구성 요소가 아니며, 빌드 시 최대한 가볍게 최적화된 웹 구성 요소의 렌더링 기능일 뿐입니다(나오는 바이트는 gzip 없이 나옵니다).

그럼 웹 구성 요소를 어떻게 로드하나요?

Vanilla JS 프로젝트에서 웹 구성 요소 로드

이렇게 하려면 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>
로그인 후 복사

여기에서는 렌더링 부분만 각 웹 구성 요소 파일에 포팅되며, 모두 신호와 Shadow DOM을 사용하여 웹 구성 요소를 생성하는 importmap에 정의된 동일한 Brisa 래퍼를 사용합니다.

웹 구성 요소의 SSR

이제 Declarative Shadow DOM 덕분에 웹 구성 요소의 SSR을 수행할 수 있습니다. counter-wc.server.js 파일은 이미 이 동작으로 컴파일되었으므로 이를 서버에서 가져와서 HTML로 렌더링하고 서버 프레임워크에 적용하기만 하면 됩니다.

다음은 JSX를 사용하지 않고 Bun.js 또는 Node.js를 사용한 예입니다.

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를 실행하면 Declarative Shadow DOM을 사용하여 렌더링된 웹 구성 요소가 포함된 HTML을 볼 수 있습니다.

브리사에 대해 더 알려주세요... 제발...

이러한 웹 구성 요소 라이브러리와 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 유형이 프로젝트에 자동으로 통합됩니다. 그리고 모든 서버 구성 요소 또는 다른 웹 구성 요소 내에서 웹 구성 요소를 사용할 수 있습니다.

Build Reactive Web Components with SSR

더 많은 내용을 알고 싶으시면 Brisa 뉴스레터를 구독하여 Brisa에 대한 최신 뉴스와 업데이트를 받아보세요. 9월 말쯤에는 출시 준비가 완료될 것으로 예상됩니다.

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을 사용하여 반응형 웹 구성 요소 구축의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!