本文へスキップ
nulldepdoc
言語: 日本語

独自 Web Components の作り方#

nulldepdoc では、ビルドツールや React を追加せずに、チーム独自のインタラクティブなコンポーネントを Markdown 内に埋め込めます。

3 ステップで追加する#

  1. static/ にバニラ JS の Custom Element を置く

    タグ名には必ずハイフン(-)を含めます(Web 標準の仕様)。

    static/hello-counter.js
    class HelloCounter extends HTMLElement {
      connectedCallback() {
        if (this._initialized) return;
        this._initialized = true;
    
        const initial = Number(this.getAttribute('start') || 0);
        let count = Number.isFinite(initial) ? initial : 0;
        const label = this.getAttribute('label') || 'Clicks';
        const resetLabel = this.getAttribute('reset-label') || 'Reset';
    
        this.innerHTML = '';
    
        const wrap = document.createElement('div');
        wrap.className = 'hc-wrap';
    
        const btn = document.createElement('button');
        btn.type = 'button';
        btn.className = 'nd-icon-btn hc-btn';
    
        const resetBtn = document.createElement('button');
        resetBtn.type = 'button';
        resetBtn.className = 'nd-icon-btn hc-reset';
        resetBtn.textContent = resetLabel;
    
        const update = () => {
          btn.textContent = `${label}: ${count}`;
        };
    
        btn.addEventListener('click', () => {
          count += 1;
          update();
        });
        resetBtn.addEventListener('click', () => {
          count = Number.isFinite(initial) ? initial : 0;
          update();
        });
    
        update();
        wrap.append(btn, resetBtn);
        this.append(wrap);
      }
    }
    
    if (!customElements.get('hello-counter')) {
      customElements.define('hello-counter', HelloCounter);
    }
  2. nulldepdoc.config.json に登録する

    nulldepdoc.config.json
    {
      "customScripts": ["/hello-counter.js"]
    }
  3. Markdown にそのまま書く

    markdown
    <hello-counter start="1" label="クリック回数" reset-label="リセット">
      <p>JavaScript が無効な環境では、このフォールバック説明文が表示されます。</p>
    </hello-counter>

実際に動いている例(<hello-counter>)#

このドキュメントサイト自身も static/hello-counter.js を登録し、以下のカスタム要素をそのまま動かしています。ボタンを押してカウントとリセットを試せます。

JavaScript が無効な環境では、このフォールバック説明文がそのまま表示されます。

このページを編集最終更新:
Built with nulldepdoc itself — 0 npm dependencies.