Use Cases

Claude Code के साथ Developing Web Components की Practical Guide

Claude Code का उपयोग करके guide to developing web components, real-world code examples के साथ।

Web Components の概要

Web Componentsは、再利用possibleなカスタムHTML要素をबनानाためのWeb標準技術 है।frameworkに依存せず、कौन साProjectでも使えるcomponentを作れ है।Claude Code का उपयोग करके、Web Componentsのdevelopmentをefficiently進められ है।

Custom Elements の基本

class AppCounter extends HTMLElement {
  private count = 0;
  private shadow: ShadowRoot;

  constructor() {
    super();
    this.shadow = this.attachShadow({ mode: "open" });
  }

  // 監視する属性
  static get observedAttributes() {
    return ["initial", "step"];
  }

  connectedCallback() {
    this.count = parseInt(this.getAttribute("initial") || "0");
    this.render();
  }

  attributeChangedCallback(
    name: string,
    oldValue: string,
    newValue: string
  ) {
    if (name === "initial" && oldValue !== newValue) {
      this.count = parseInt(newValue);
      this.render();
    }
  }

  private get step(): number {
    return parseInt(this.getAttribute("step") || "1");
  }

  private render() {
    this.shadow.innerHTML = `
      <style>
        :host {
          display: inline-flex;
          align-items: center;
          gap: 8px;
          font-family: system-ui, sans-serif;
        }
        button {
          padding: 4px 12px;
          border: 1px solid #ccc;
          border-radius: 4px;
          cursor: pointer;
          font-size: 16px;
        }
        button:hover {
          background-color: #f0f0f0;
        }
        .count {
          font-size: 24px;
          font-weight: bold;
          min-width: 40px;
          text-align: center;
        }
      </style>
      <button id="dec">-</button>
      <span class="count">${this.count}</span>
      <button id="inc">+</button>
    `;

    this.shadow.getElementById("dec")!.addEventListener("click", () => {
      this.count -= this.step;
      this.render();
      this.dispatchEvent(new CustomEvent("change", { detail: this.count }));
    });

    this.shadow.getElementById("inc")!.addEventListener("click", () => {
      this.count += this.step;
      this.render();
      this.dispatchEvent(new CustomEvent("change", { detail: this.count }));
    });
  }
}

customElements.define("app-counter", AppCounter);

use करने का तरीका:

<app-counter initial="10" step="5"></app-counter>

Lit frameworkでefficiency improvement

import { LitElement, html, css } from "lit";
import { customElement, property, state } from "lit/decorators.js";

@customElement("app-todo-list")
class AppTodoList extends LitElement {
  static styles = css`
    :host {
      display: block;
      max-width: 400px;
      font-family: system-ui, sans-serif;
    }
    .input-row {
      display: flex;
      gap: 8px;
      margin-bottom: 16px;
    }
    input {
      flex: 1;
      padding: 8px;
      border: 1px solid #ccc;
      border-radius: 4px;
    }
    ul {
      list-style: none;
      padding: 0;
    }
    li {
      display: flex;
      align-items: center;
      gap: 8px;
      padding: 8px 0;
      border-bottom: 1px solid #eee;
    }
    .done {
      text-decoration: line-through;
      color: #999;
    }
  `;

  @state()
  private todos: Array<{ text: string; done: boolean }> = [];

  @state()
  private newTodo = "";

  private addTodo() {
    if (!this.newTodo.trim()) return;
    this.todos = [...this.todos, { text: this.newTodo, done: false }];
    this.newTodo = "";
  }

  private toggleTodo(index: number) {
    this.todos = this.todos.map((todo, i) =>
      i === index ? { ...todo, done: !todo.done } : todo
    );
  }

  render() {
    return html`
      <div class="input-row">
        <input
          .value=${this.newTodo}
          @input=${(e: InputEvent) =>
            (this.newTodo = (e.target as HTMLInputElement).value)}
          @keyup=${(e: KeyboardEvent) => e.key === "Enter" && this.addTodo()}
          placeholder="taskを入力..."
        />
        <button @click=${this.addTodo}>add</button>
      </div>
      <ul>
        ${this.todos.map(
          (todo, i) => html`
            <li>
              <input
                type="checkbox"
                .checked=${todo.done}
                @change=${() => this.toggleTodo(i)}
              />
              <span class=${todo.done ? "done" : ""}>${todo.text}</span>
            </li>
          `
        )}
      </ul>
    `;
  }
}

スロットによるコンポジション

@customElement("app-card")
class AppCard extends LitElement {
  static styles = css`
    :host {
      display: block;
      border: 1px solid #e2e8f0;
      border-radius: 8px;
      overflow: hidden;
    }
    .header {
      padding: 16px;
      background: #f8fafc;
      border-bottom: 1px solid #e2e8f0;
    }
    .body {
      padding: 16px;
    }
    .footer {
      padding: 16px;
      background: #f8fafc;
      border-top: 1px solid #e2e8f0;
    }
  `;

  render() {
    return html`
      <div class="header">
        <slot name="header"></slot>
      </div>
      <div class="body">
        <slot></slot>
      </div>
      <div class="footer">
        <slot name="footer"></slot>
      </div>
    `;
  }
}
<app-card>
  <h2 slot="header">cardタイトル</h2>
  <p>cardの本文がयहांに入り है।</p>
  <button slot="footer">アクション</button>
</app-card>

Reactとのintegration

import { useRef, useEffect } from "react";

function CounterWrapper({
  initial,
  onChange,
}: {
  initial: number;
  onChange: (value: number) => void;
}) {
  const ref = useRef<HTMLElement>(null);

  useEffect(() => {
    const el = ref.current;
    const handler = (e: Event) => {
      onChange((e as CustomEvent).detail);
    };

    el?.addEventListener("change", handler);
    return () => el?.removeEventListener("change", handler);
  }, [onChange]);

  return <app-counter ref={ref} initial={initial} />;
}

Claude Code सेのutilization

Web ComponentsdevelopmentをClaude Code को requestする例 है।スタイリングにはTailwind CSSutilization法、component設計の参考 के रूप मेंcode分割・遅延読み込みもदेखें。

Litका उपयोग करकेデザインシステムのcomponentを作って。
- app-button, app-input, app-modal, app-toast
- CSS Custom Propertiesでthemesupport
- TypeScriptで型safeに
- Storybookでドキュメント化して

Web Componentsの仕様はMDN Web Componentsをदेखें。Claude Codeके details के लिएofficial documentationでconfirmでき है।

Summary

Web Componentsはframework非依存の再利用possibleなUI buildできる標準技術 है।Claude Code का उपयोग करके、Custom ElementsやLitのimplementationをefficiently進められ、既存Projectとのintegrationもスムーズに行え है।

#Claude Code #Web Components #Custom Elements #Shadow DOM #Lit